今天在自己尝试制作App,使用以前的老办法自定义一个title,写着写着发觉很不方便:1,每个界面都有title,一直重复为每个界面添加特别麻烦。2,不同的界面有不同的要求,有的界面之又返回键,有的界面有返回键和更多选项。
虽然以上两个问题非常说起来很简单,但是做起来代码量真的非常大,于是开始想有没有一种办法可以用几行代码就控制title的添加与移除?更改title名称?或者说为每个右选项按钮设置不同的点击事件?
答案肯定是有的,如果是新手,请跟着文章的思路一直往下走,不要急。这里就要用到自定义view的知识啦,首先我们创建一个TitleBar的类,并且制作一个title样式:
xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tool="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="60dp" android:background="#9089B3"> <ImageView android:id="@+id/back" android:layout_width="60dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:background="@drawable/back" android:visibility="gone" /> <TextView android:id="@+id/activity_title" android:layout_width