[mobilesafe] 11_(难)自定义组合控件2-在xml中添加属性并可以使用该属性

Android 4.0

自定义组合控件2-在xml中添加属性并可以使用该属性

系统中,控件在xml中属性的定义\sdk\platforms\android-18\data\res\values\attrs.xml
<resource>
<declare-styleable name="TextView"
       <!-- Text to display. -->
        <attr name="text" format="string" localization="suggested" />
        <!-- Hint text to display when the text is empty. -->
        <attr name="hint" format="string" />
</declare-styleable>
</resource>

自定义控件步骤(添加方法和属性):
1. 创建一个自定义的组合控件 继承一个布局 RelativeLayout 或者LinearLayout ViewGroup
2. 实现构造方法  在构造方法里面设置要显示的内容
   View.inflate(context, R.layout.setting_view_layout, this);
3.添加自定义的属性. 报错
hacket:title="hacket标题"  
4. 声明命名空间,报错,还没有定义该属性
xmlns:itheima="http://schemas.android.com/apk/res/<应用程序的包名和清单文件一致>"

xmlns:hacket="http://schemas.android.com/apk/res/cn.zengfansheng.mobilesafe"
5.res\values\attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SettingView">  <!-- name:自定义样式名称 -->
        <attr name="title" format="string" />  <!-- 自定义属性  -->
        <attr name="desc_on" format="string" />
        <attr name="desc_off" format="string" />
    </declare-styleable>
</resources>
6.观察R文件 styleable.SettingView的数组 保存的所有的属性.
public final class R {
    public static final class attr {
        
public static final int desc_off=0x7f010002;
        public static final int desc_on=0x7f010001;
        public static final int title=0x7f010000;
    }
       public static final class styleable {
             
        public static final int[] SettingView = {
            0x7f010000, 0x7f010001, 0x7f010002
        }; 
              
public static final int SettingView_desc_off = 2;  
              public static final int SettingView_desc_on = 1;  
        public static final int SettingView_title = 0;  
       }      
}
7. 回到自定义组合控件的java代码. 在两个参数的构造方法里面
public SettingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initViewFromXml(context);
    System.out.println("SettingView两个参数的构造方法。。。");
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingView);
    // 把自定义的属性和attrs的集合建立一个对应关系
    String desc_on = typedArray.getString(R.styleable.SettingView_desc_on);
    String desc_off = typedArray.getString(R.styleable.SettingView_desc_off);
    typedArray.recycle();
}
8.  用完typedArray , typedArray.recycle();  释放资源
9. 扩展自定义控件的一些方法.设置标题 设置内容 响应点击事件