Android自定义控件实现标题栏

方式一:

先建立一个title.xml

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#00ff00"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="返回"
android:background="#fff"/>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="这是标题栏"
android:gravity="center"
android:layout_weight="1"
android:textSize="24sp"
android:textColor="#fff"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="编辑"
android:background="#fff"/>
</LinearLayout>
</LinearLayout>
标题栏做的丑,不过不影响学。
在activity_main.xml中通过include引入
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/title"/>
</LinearLayout>
在MainActivity中通过调用getSupportActionBar()方法获取ActionBar的实例,在调用ActionBar的hide()方法将标题栏隐藏起来
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main1);

ActionBar actionBar=getSupportActionBar();
if (actionBar!=null){
actionBar.hide();
}
}
}
方式二
在title.xml的基础上。
新建一个活动 TitleLayout,继承父类Linearlayout
代码如下:
 public TitleLayout(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button back=findViewById(R.id.button1);
Button edit=findViewById(R.id.button2);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"你点击了编辑按钮",Toast.LENGTH_LONG).show();
}
});
}
}
实现返回和编辑按钮的监听事件
 
在activity_main.xml中修改代码:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<include layout="@layout/title"/>-->
<com.example.administrator.uilayouttest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>



猜你喜欢

转载自www.cnblogs.com/hy-nobug/p/12130118.html