Android自定义组合控件

来源:互联网 发布:人工智能三贤者理论 编辑:程序博客网 时间:2024/06/05 18:53

一般的步骤:

1.      定义一个xml布局文件,这个布局文件中的内容是:

你想要自定义的控件的所有组件,分开来写

2. 定义一个java类,继承你想定义的内容,比如继承RelativeLayout

3.  在activity的xml中,使用java类中自定义的控件

 

接下来举例:

 目标如下:


点击设置是否自动更新,checkbox也会被选中,因此需要将,2个textview,checkbox设置为一个组合控件。


第一步:

定义一个RalativeLayout,实现



第二步:

创建一个Java类,继承RelativeLayout,并在java类中加载第一步实现的布局文件

package com.android.programmer_C.ui;import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.widget.CheckBox;import android.widget.RelativeLayout;import android.widget.TextView;import com.android.programmer_pc.mobilesafe.R;/** * Created by Programmer_PC on 2016/6/27. */public class SettingItemView extends RelativeLayout {    private CheckBox cb_status;    private TextView tv_desc;    private TextView tv_title;    private  String desc_on;    private String desc_off;    private void iniView(Context context){        //把一个布局文件---》View 并且加载在SettingItemView        View.inflate(context, R.layout.setting_item_view, this);        cb_status = (CheckBox) this.findViewById(R.id.cb_status);        tv_desc = (TextView) this.findViewById(R.id.tv_desc);        tv_title = (TextView) this.findViewById(R.id.tv_title);    }    public SettingItemView(Context context) {        super(context);    }    public SettingItemView(Context context, AttributeSet attrs) {        super(context, attrs);        iniView(context);    }    public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {        super(context, attrs, defStyleAttr, defStyleRes);    }    /**     * 校验组合控件是否选中     */    public boolean isChecked(){        return cb_status.isChecked();    }    /**     * 设置组合控件的状态     */    public void setChecked(boolean checked){        if(checked){            setDesc(desc_on);        }else{            setDesc(desc_off);        }        cb_status.setChecked(checked);    }    /**     * 设置 组合控件的描述信息     */    public void setDesc(String text){        tv_desc.setText(text);    }}

第三步:直接使用上述定义的组合控件

0 0
原创粉丝点击