组合式控件
多个零散的控件当一个控件用
1。抽取公用的布局代码,到一个布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingRight="15dp">
<TextView
android:id="@+id/tv_auto_updata"
android:layout_centerVertical="true"
android:textSize="16sp"
android:text="自动设置更新"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/iv_toggle"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:src="@mipmap/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
2。定义一个 类,这个类继承是由规则的,布局的跟标签是什么类型,就必须继承什么类型的;
public class SettingItemView extends RelativeLayout
3。导入布局,把布局加入到容器中
public SettingItemView(Context context, AttributeSet attrs) {
super(context, attrs);
//第三个参数如果为null:则表示不要将布局加入到容器中
//如果是this:则表示将布局加入到当前容器中
//容器就是当前类
View.inflate(context , R.layout.setting_item_view , this);
}
4。使用组合式控件
<com.myself.mobilesafe.View.SettingItemView
android:background="@drawable/seletor_siv_first"
myattrs:title="设置自动更新"
android:id="@+id/siv_auto_updata"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
自定义属性
1。首先在values文件夹下创建一个attrs.xml文件
2。在文件中声明属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--这里的name,一般情况下写的是类名-->
<declare-styleable name="SettingItemView">
<!--属性名为title,属性的数据类型是string类型的-->
<attr name="title" format="string"/>
</declare-styleable>
</resources>
3。在布局文件中声明命名空间
//将android换成包名com.myself.mobilesafe
xmlns:myattrs="http://schemas.android.com/apk/res/com.myself.mobilesafe"
4。在控件中使用属性
<com.myself.mobilesafe.View.SettingItemView
android:background="@drawable/seletor_siv_first"
myattrs:title="设置自动更新"
android:id="@+id/siv_auto_updata"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
5。在自定义组合式控件中获取属性值
//得到名为settingitemview下的所有属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
//得到自己定义的title属性数值
String title = typedArray.getString(R.styleable.SettingItemView_title);
mTvAutoUpdata.setText(title);
//释放资源
typedArray.recycle();