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

来源:互联网 发布:淘宝加盟公司靠谱吗 编辑:程序博客网 时间:2024/06/05 12:38

                首先在项目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);    }
这样,就可以将我们的自定义属性读取出来并且显示到控件上了

0 0
原创粉丝点击