自定义组合控件

来源:互联网 发布:淘宝店铺装修特效 编辑:程序博客网 时间:2024/06/04 18:51

1        新建一个类继承一个布局并实现其中的3个方法

                  

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);

            

2        在第三个方法中加载一个布局(其中包含要组合的控件)

               找到对应的控件

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);

                   
//自定义组合控件中的标题描述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);


                   

//自定义组合控件中的标题描述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);

//获取自定义以及原生属性的操作,写在此处,AttributeSet attrs对象中获取initAttrs(attrs);

                   

//自定义组合控件中的标题描述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);
                   
//自定义组合控件中的标题描述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);

StringNAMESPACE="http://schemas.android.com/apk/res/com.example.pc.myapplication"
//通过名空间+属性名称获取属性值private void initAttrs(AttributeSet attrs) {    //通过名空间+属性名称获取属性值    mDestitle=attrs.getAttributeValue(NAMESPACE,"destitle");    mDesoff=attrs.getAttributeValue(NAMESPACE,"desoff");    mDeson=attrs.getAttributeValue(NAMESPACE,"deson");}

3  要在value下新建一个attrs.xml文件

                 

<resources>    <declare-styleable name="SettingItemView">        <attr name="destitle" format="string"/>        <attr name="desoff" format="string"/>        <attr name="deson" format="string"/>    </declare-styleable></resources>

4   使用组合控件

        注意控件的xmlns 格式  前面的mobilesafe 算便设置   最后加包名

<com.example.pc.myapplication.view.SettingItemView    xmlns:mobilesafe="http://schemas.android.com/apk/res/com.example.pc.myapplication"    android:id="@+id/siv_update"    android:layout_width="match_parent"    android:layout_height="wrap_content"    mobilesafe:destitle="自动更新设置"    mobilesafe:desoff="自动更新已关闭"    mobilesafe:deson="自动更新已开启"    ></com.example.pc.myapplication.view.SettingItemView>

5   总结使用过程

       先加载一个布局1,在布局中使用组合控件(一个继承过后的类),新建attrs文件,在布局1中对页面进行监听





                   
//自定义组合控件中的标题描述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);