Android之自定义属性简单使用-----获取自定义属性

                首先在项目values目录下创建attrs文件,name这里是类名(eclipse全类名)

              

<resources>
    <declare-styleable name="SettingItemView">
        
        <attr name="desTitle" format="string"/>
        <attr name="desOff" format="string"/>
        <attr name="desOn" format="string"/>
        
    </declare-styleable>
</resources>
写好自定义属性attrs之后,就开始在我们的项目中使用。

<com.example.administrator.iphoneguard.weight.SettingItemView
    xmlns:iphone="http://schemas.android.com/apk/res/com.example.administrator.iphoneguard"
    android:id="@+id/id_set_one"
    android:layout_width="match_parent"
    iphone:desTitle = "我是第一个更新的头部"
    iphone:desOff="我是第一个被关的"
    iphone:desOn = "我是第一个被打开的"
    android:layout_height="wrap_content">
当然,这个时候运行起来并不能看到我们设定的属性被显示出来,还需要在控件的构造方法中,读取到我们自定义的属性

public class SettingItemView extends RelativeLayout {
    private static final String NAMESPACE = "http://schemas.android.com/apk/res/com.example.administrator.iphoneguard";
    private CheckBox cb_box;
    private TextView textTitle,textDes;
    private String desTitle,desOff,desOn;

    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);
        //View.inflate (上下文环境,布局文件,SettingItemView的对象)
        View view = View.inflate(context, R.layout.setting_item_view,this);

//        View view1 = View.inflate(context,R.layout.setting_item_view,null);
//        this.addView(view1);

        textTitle = (TextView) findViewById(R.id.id_tv_title);
        textDes = (TextView) findViewById(R.id.id_tv_des);
        cb_box = (CheckBox) findViewById(R.id.id_check_box);

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

    private void initAttrs(AttributeSet attrs) {
//        TLog.log("AttributeSet的属性个数为 = " +attrs.getAttributeCount());
            for (int i = 0;i<attrs.getAttributeCount();i++){
                TLog.log("AttributeSet的属性名字是 = "+attrs.getAttributeName(i)+"  AttributeSet的属性名字是 = "+attrs.getAttributeValue(i));
            }
        desTitle = attrs.getAttributeValue(NAMESPACE,"desTitle");
        desOff = attrs.getAttributeValue(NAMESPACE,"desOff");
        desOn = attrs.getAttributeValue(NAMESPACE,"desOn");

        textTitle.setText(desTitle);
        textDes.setText(desOff);
    }
这样,就可以将我们的自定义属性读取出来并且显示到控件上了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值