当一系列控件组成的条目,需要重复使用时,为了减轻xml中的代码,所以讲一系列控件进行整合:如下步骤
自定义组合控件:
1.将已经编写好的布局文件,抽取到一个类中去做管理,下次还需要使用此布局结构的时候,
直接使用组合控件对应的对象.
2.将组合控件的布局,抽取到单独的一个xml中
3.通过一个单独的类,去加载此段布局文件.
如下演示:
上面的界面的简图,大概构成没条目就是 两个Textview 一个CheckBox 还有一根线。
如果反复去写这些会很麻烦,所以先写出一条,如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自动更新设置"
android:textColor="#000"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_title"
android:text="自动更新已关闭"
android:textColor="#000"
android:textSize="18sp" />
<CheckBox
android:id="@+id/cb_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@id/tv_des"
android:background="#000" />
RelativeLayout>
LinearLayout>
再新建一个类
package com.chase.cn.phonesafe.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import com.chase.cn.phonesafe.R;
/**
* Created by Chase on 2016/12/7.
*/
public class SettingItemView extends RelativeLayout {
public SettingItemView(Context context) {
this(context,null);
}
public SettingItemView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//xml ----> view 将设置界面的条目转换为View对象
//(后面的inflate的三个参数,最后一个在这里比较重要,就是这个控件要放在哪里?)
View.inflate(context, R.layout.setting_item_view,this);
}
}
注意这句
View.inflate(context, R.layout.setting_item_view,this);
这里最后一个参数添this,因为是这样的:现在inflate了以后,是把xml文件转化为view,如下:
但是要这个整个view丢进settingItemView中去,最后一个参数就要说this:
在需要使用的xml中就可以直接定义了:
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
"设置中心"
style="@style/TitleStyle"/>
<com.chase.cn.phonesafe.view.SettingItemView
android:layout_width="match_parent"
android:layout_height="wrap_content">
com.chase.cn.phonesafe.view.SettingItemView>
<com.chase.cn.phonesafe.view.SettingItemView
android:layout_width="match_parent"
android:layout_height="wrap_content">
com.chase.cn.phonesafe.view.SettingItemView>