##使用场景
在开发中,或许一个业务需求中会出现很多系统控件组合成的布局,并且经常需要复用。
比如下图中 qq或者微博的title栏,在一款app中,可能不同的界面 类似的view要出现很多次,这个时候 就可以设计自己的view控件,就称为组合控件吧。
创建灵活的模板,通过调用自己的view,提高开发效率、降低耦合度。好处不言而喻
这边以微博的title为例,创建一个组合控件
首先分析一下,上图微博的当前页面似乎包含了三四个控件,具体看你要怎么做了:
ImageButton、TextView+DrwableRight、ImageButton
或者是 ImageButton、TextView+ImageView、ImageButton。
这边以三个控件为例,创建一个布局,在里面添加三个控件,然后控制其属性
创建控件
- 为控件添加自定义属性:
在资源文件res-values文件夹下创建一个xml文件attrs,这时候可以考虑一下控件中需要哪些属性,比如(左边的控件是否可见、中间的text文本、整个title的背景等等),可以根据需求去添加。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TitleBar">
<!--定义自己想要的属性,在代码中引用,format指的是返回到代码中的格式-->
<!--中间文本-->
<attr name="centerText" format="string" />
<!--中间的空间是否显示右侧的图标-->
<attr name="centerIsShowRightIcon" format="string" />
<!--title的背景色//背景可能会包括颜色或者是资源文件 所以format这样表示-->
<attr name="titleBackground" format="reference|color" />
<!--左右两边的图-->
<attr name="leftImageDrwable" format="reference" />
<attr name="rightImageDrwable" format="reference" />
</declare-styleable>
</resources>
- 创建控件,并加入系统自带控件
使用布局加入控件,并关联
创建一个布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@android:color/holo_green_dark"
tools:context="com.example.skym.customviewcontrol.MainActivity">
<ImageButton
android:id="@+id/ib_left"
a