android 自定义组合控件

来源:互联网 发布:男士手表推荐 知乎 编辑:程序博客网 时间:2024/06/01 20:37

当一个布局中存在多个控件,然而这个布局多次使用,从而炫耀自定义组合控件,方便调用,减少代码量,案例如下:

SettingItemView自定义控件,集成RelativeLayout

/**
 * 自定义设置页面点击条目
 *
 * @author Administrator
 *
 */
public class SettingItemView extends RelativeLayout {

    private CheckBox cb_box;
    private TextView tv_des;

    public SettingItemView(Context context) {
        // super(context);
        this(context, null);

    }

    public SettingItemView(Context context, AttributeSet attrs) {
        // super(context, attrs);
        this(context, attrs, 0);
    }

    public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View.inflate(context, R.layout.setting_item_view, this);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_des = (TextView) findViewById(R.id.tv_des);
        cb_box = (CheckBox) findViewById(R.id.cb_box);

    }

    /**
     * 获取 cb_box选中状态
     *
     * @return cb_box是否选中
     */
    public boolean isCheck() {
        return cb_box.isChecked();
    }

    /**
     * 设置cb_box选中状态,并更新条目描述值
     *
     * @param isCheck
     *            cb_box是否选中
     */
    public void setCheck(boolean isCheck) {
        cb_box.setChecked(isCheck);
        if (isCheck) {
            tv_des.setText("自动更新已开启");
        } else {
            tv_des.setText("自动开启已关闭");
        }
    }

}

setting_item_view 布局文件

<?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: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:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/tv_des"
        android:background="#000" />

</RelativeLayout>


在activity布局中调用

 <com.example.shoujiweishi.ui.SettingItemView
        android:id="@+id/siv_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />