自訂view中自訂屬性的用法.,自訂view

來源:互聯網
上載者:User

自訂view中自訂屬性的用法.,自訂view

有時候我們自訂的view需要用到有自己定義的屬性。

首先定義自己的屬性,在res/values/attrs.xml中定義,xml檔案如下:

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name = "myView">        <attr name = "text" format = "string" />        <attr name = "textSize" format = "dimension"/>        <attr name = "textColor" format = "color"/>        <attr name = "rectColor" format = "color"/>    </declare-styleable></resources>
name屬性很重要,關係到以後的調用。

format為屬性的類型,這裡列舉了幾種基本的資料類型,注意textSize等關係到大小的屬性格式為dimension。


在布局檔案中的使用。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:my="http://schemas.android.com/apk/res/com.example.myview"     android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    >    <com.example.myview.MyView         android:layout_width="100dp"        android:layout_height="100dp"        my:text = "點擊開始計數"        my:textColor = "#ffff0000"        my:textSize = "21sp"        my:rectColor = "#ff00ff00"        /></RelativeLayout>
xmlns:my="http://schemas.android.com/apk/res/com.example.myview" 為使用

my欄位調用自訂屬性的關鍵代碼。

使用my:XXX時並不會驗證屬性的正確性。

但是在自訂view代碼中擷取屬性值的時候會進行驗證。

擷取屬性值對自定view進行初始化。

//擷取xml檔案中的屬性數組private void initAttrs(AttributeSet attrs) {mPanit = new Paint();mBound = new Rect();setOnClickListener(this);//和attr.xml中的屬性列表對應上TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);String text = ta.getString(R.styleable.myView_text);setText(text);int textSize = ta.getDimensionPixelOffset(R.styleable.myView_textSize, 26);setTextSize(textSize);int color = ta.getColor(R.styleable.myView_textColor, 0xff000000);setTextColor(color);int rectColor = ta.getColor(R.styleable.myView_rectColor, 0xff000000);setRectColor(rectColor);ta.recycle();}
AttributeSet attrs為xml中的屬性和它所對應的值。

TypedArray ta = getContext().obtainStyledAttributes(attrs,R.styleable.myView);

只擷取自訂屬性名為myView中的屬性。並且賦值給TypeArray ta。

之後便可根據 ta 擷取擷取對應的屬性值了。

至於擷取的屬性值該怎麼用,就要看你自己的了。



android自訂控制項怎自訂屬性?

可以在attrs.xml中定義自己的屬性。不過這種自訂的東西還是寫在代碼裡比較好,動態載入,方便控制。
 
android自訂view 屬性使用問題

不可以,自訂的只能運行了看,只有系統的才可以在Graphical Layout模式下看
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.