Android自訂XML屬性

來源:互聯網
上載者:User

標籤:枚舉   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屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.