Android自定义UI模板图文详解【附源代码】(2)

第三步:引用我们定义的控件
自定义好控件之后,我们就可以使用自定义的控件了,在主布局的xml文件中引用我们自定义的控件。自定义控件的前三个属性都是以android:开头,这表示这些属性都是系统的,后面的属性以custombar开头,表示这些属性都是我们自定义的,为了能够使用自定义的custombar,我们需要在RelativeLayout中添加一句:

xmlns:custombar="http://schemas.android.com/apk/res/com.example.mytoolbar"

注意后面的com.example.mytoolbar是你应用的包名称。如果阁下使用的不是eclipse而是android studio,那么这一行不用这么麻烦,只需要写上:

xmlns:custombar="http://schemas.android.com/apk/res-auto"

我们自定义的属性就是我们在atts.xml中声明的要设置的属性。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custombar="http://schemas.android.com/apk/res/com.example.mytoolbar" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.mytoolbar.MyToolBar android:id="@+id/mytoolbar" android:layout_width="match_parent" android:layout_height="48dp" custombar:leftBackground="@android:color/holo_blue_light" custombar:leftText="返回" custombar:leftTextColor="@android:color/black" custombar:rightBackground="@android:color/holo_blue_light" custombar:rightText="更多" custombar:rightTextColor="@android:color/black" custombar:title="标题栏" custombar:titleTextColor="@android:color/black" custombar:titleTextSize="18sp" > </com.example.mytoolbar.MyToolBar> </RelativeLayout>

做完这些工作之后,运行你的项目,就能看到我们在文章开头给出的那个画面了。

第四步:为自定义控件添加事件

好像还少点什么,是的,我们的控件都还没有点击事件。要给事件设置点击事件,需要先在自定义控件中声明一个事件接口,并声明一个接口的实例:

private OnToolBarClickListener listener; public interface OnToolBarClickListener { /** * 左边按钮点击事件 */ public void leftClick(); /** * 右边按钮点击事件 */ public void rightClick(); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/296d42658a5b8e652c6781bf70b7b340.html