码迷,mamicode.com
首页 > 移动开发 > 详细

Android自定义XML属性

时间:2016-11-25 01:06:30      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:枚举   relative   system   utf-8   get   str   for   idt   ima   

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="RatioLayout">
        <attr name="picRatio" format="float" />
        <attr name="relative">
            <enum name="width" value="0" />
            <enum name="height" value="1" />
        </attr>
    </declare-styleable>

</resources>

上面分别写了两种典型的XML属性的配置,需要在values-attrs文件中编写。

第一种就是name,后面直接跟一个类型,这样可以在XML中自己任意配置。

第二种是枚举,这样就只能选择固定的属性了。

那么,问题来了,如何在View中对这些属性读取呢??下面介绍两种方法。

1、

        <com.itheima.googleplay_8.views.RatioLayout
            xmlns:itheima="http://schemas.android.com/apk/res-auto"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            itheima:relative="width"
            itheima:picRatio="2.43" >
    public RatioLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);

        mPicRatio = typedArray.getFloat(R.styleable.RatioLayout_picRatio, 0);

        mRelative = typedArray.getInt(R.styleable.RatioLayout_relative, RELATIVE_WIDTH);

        typedArray.recycle();
    }

2、

    <com.example.myview.MyView
        android:id="@+id/myView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        yueqing:content="内容"
        yueqing:title="标题" >
    </com.example.myview.MyView>
public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);

        View inflate = View.inflate(context, R.layout.myview, null);
        CheckBox cb = (CheckBox) inflate.findViewById(R.id.cb);
        TextView tv = (TextView) inflate.findViewById(R.id.tv);
        String content = attrs.getAttributeValue(
                "http://schemas.android.com/apk/res/com.example.myview",
                "content");
        if (!cb.isChecked()) {
            tv.setText(content);
        }
        
        this.addView(inflate);
        int attributeCount = attrs.getAttributeCount();
        System.out.println(attributeCount + ">>>>>>>>>>>>>>>>");
    }

 

 

Android自定义XML属性

标签:枚举   relative   system   utf-8   get   str   for   idt   ima   

原文地址:http://www.cnblogs.com/tinyclear/p/6100042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!