想自定义一个标题栏,有一种简单的做法,引入布局文件就可以啦。
我们来模仿一个简单的标题栏,即左右各一个按钮,中间一个文本。也就是说我们只要两个button和一个TextView即可
1.新建一个布局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"
android:background="@drawable/title_bg">//整个布局的背景图
<Button
android:id="@+id/title_back"
android:layout_width="77dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/qod"
android:text="返回"
android:textColor="@android:color/darker_gray" />
<TextView
android:id="@+id/title_text"
android:layout_width="214dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginTop="7dp"
android:gravity="center"
android:text="文本中心"
android:textColor="@android:color/background_dark"
android:textSize="24sp" />
<Button
android:id="@+id/title_set"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/gwf"
android:textColor="@android:color/darker_gray" />
</LinearLayout>
这个文件我们采用LinearLayout,两个按钮一个文本,使用三张图片来为布局和空间指定一个背景,你也可以直接填充颜色,title_bg.png,qod.png,gwf.png分别用于标题栏,返回按钮和设置按钮的背景。
上述文件得到的布局样式图如下:
2.别忘了在MainAcitivity中将系统自带的标题栏隐藏掉,代码如下:
getSupportActionBar().hide();
3.可在MainAcitivity中注册按钮的***,用于实现某种效果,代码如下:
Button back = (Button) findViewById(R.id.title_back);
back.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Toast.makeText(MainActivity.this , "返回键被点击" , Toast.LENGTH_SHORT).show();
}
});
4.运行程序,点击返回按钮,效果图如下(其他的不用管,只需关注标题栏效果即可)