Android之 自訂屬性 的使用

來源:互聯網
上載者:User

1.自訂一個view檔案MyView.java

2.定義自訂屬性檔案values/attrs.xml

<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <declare-styleable name="MyAtrr">
        <attr name="textcolor" format="color"/>
        <attr name="textsize" format="dimension"/>
    </declare-styleable>
</resources>

3.在主布局檔案中使用自訂view和自訂屬性

    xmlns:MySpace="http://schemas.android.com/apk/res/com.example.attrtest" //添加命名空間,紅色的為包名

 <com.example.attrtest.MyView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        MySpace:textsize="25dp"
        MySpace:textcolor="#FF00FF00"   
        />

注意:給textcolor賦值時,是8位,不然在程式中會擷取失敗

4.在自訂view的初始化時擷取自訂屬性

自訂view在布局檔案中初始化時,調用2個參數的建構函式

TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyAtrr);
int textcolor=ta.getColor(R.styleable.MyAtrr_textcolor, Color.RED);   
float textsize=ta.getDimension(R.styleable.MyAtrr_textsize, 30);

兩個擷取函數的第二個參數都是在沒有添加自訂屬性時給定的預設值

就這麼簡單。

上原始碼:http://download.csdn.net/detail/wulongtiantang/5134371

相關文章

聯繫我們

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