提起标题栏,相信大家都不会陌生,因为它太常见了。标题栏一般出现在整个程序的上面用作界面提示和返回等操作。一般是一种组合式自定义控件,下面让我们一起学习来学习一下标题栏的制作吧。
1.制作布局
标题栏其实是一种自定义控件,创建这种复合组件首先第一步就是创建一个包含多个组件的viewgroup,通常我们把一个TextView和两个Button放进去,这是一种比较经典的界面,你可能会说有的界面只有一个按钮啊,其实实现这种效果也不难,我们可以在程序中动态地设置界面的显示与隐藏嘛。那我们现在新建一个名字叫title.xml的布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/tab_bg">
<Button
android:id="@+id/title_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Back" />
<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#fff"
android:textSize="25sp"
android:text="Title"/>
<Button
android:id="@+id/title_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:layout_margin="5dp" />
</LinearLayout>
创建好这个复合组件的布局文件后,我们就可以在任意一个activity的布局文件中使用啦,使用的方法也很简单,比如我们想在MainActivity中使用,那就在MainActivity对应的布局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"/>
</LinearLayout>
看到没,其实就是一句话用include把它引用过来就可以了。让我们来看看效果吧:
我就没有去网上为这两个Button去找好看的背景了哈,所以使用了原生的Button样式,我着重介绍下设计的方法。这样我们就把这包含三个控件的复合组件当做一个整体了,可以在任何布局中使用到它了。不过目前的话除了表面上有点自定义标题栏的样子,其实是完全没有实际使用效果,因为你点击上面的Button,没有任何应答。我们当然不会希望这个标题栏只能用来看的吧,那我们就下面动手为它设置监听器吧!
2.制作自定义控件
其实刚刚我们制作的布局文件如果直接被引入到每个activity中的话,那么在每个activity中我们都要先获取到控件实例,然后为控件注册监听器,然后重写监听方法…….比如上面的Back按钮其实在大多activity中都是销毁当前的活动,这个按钮的功能可能在所有的活动中都是相同的,要是直接通过引入布局的话,就要为每个按钮注册相同的监听事件了。可以预料到,通过这种方式写的代码冗余度会非常高,太多的重复代码。那有什么办法能够避免这么做,避免写太多重复代码?
这种情况下,我们可以通过自定义控件的方式来解决,自定义控件其实很简单,新建一个类继承ViewGroup,然后重写它的带有参数的构造方法,代码如下所示:
public class TitleLayout extends LinearLayout {
private Button titleLeft;
private Button titleRight;
private TextView titleText;
public TitleLayout(Context context, AttributeSet attributes){
super(context,attributes);
LayoutInflater.from(context).inflate(R.layout.title,this);
titleLeft=(Button) findViewById(R.id.title_left);
titleRight=(Button) findViewById(R.id.title_right);
titleLeft.setOnClick