自訂群組件樣本:使用attrs.xml檔案定製RadioButton

來源:互聯網
上載者:User

 

1.在res/values下建立attrs.xml

 

<declare-styleable name="MyRadioButton"> 

        <attr name="str" format="string"/> 

</declare-styleable> 

 

MyRadioButton為組件名字,隨意起,attr標籤定義組件的屬性,name對應的是屬性名稱,format是屬性的類型,具體可參見《[Android]attrs.xml檔案中屬性類型format值的格式》。

 

2.在自訂的組件中使用attrs.xml檔案的定義

 

public class MyRadioButton extends RadioButton { 

    private String url; 

     

    public MyRadioButton(Context context, AttributeSet attrs) { 

        super(context, attrs); 

        TypedArray taArray = context.obtainStyledAttributes(attrs,R.styleable.MyRadioButton); 

        this.url = taArray.getString(R.styleable.MyRadioButton_str); 

        taArray.recycle(); 

    } 

 

    public String getUrl() { 

        return url; 

    } 

 

    public void setUrl(String url) { 

        this.url = url; 

    } 

     

 

a. TypedArray是存放資源R.styleable.MyRadioButton指定的屬性集合。

b. 通過getXXX()擷取屬性值。

c. recycle()結束綁定

3.在布局檔案中使用

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    android:orientation="vertical" > 

    <RadioGroup  

       android:layout_width="fill_parent" 

       android:layout_height="wrap_content" 

       > 

        <net.csdn.blog.wxg630815.MyRadioButton 

            android:layout_width="fill_parent" 

            android:layout_height="wrap_content" 

            android:id="@+id/myradio1" 

            demo:str="1.csdn.net" 

            /> 

        <net.csdn.blog.wxg630815.MyRadioButton 

            android:layout_width="fill_parent" 

            android:layout_height="wrap_parent" 

            android:id="@+id/myradio2" 

            demo:str="2.csdn.net" 

            /> 

        

   </RadioGroup> 

 

</LinearLayout> 

 

注意:xmlns:demo="http://schemas.android.com/apk/res/net.csdn.blog.wxg630815"

只有聲明這句以後,url屬性才會被布局檔案識別。net.csdn.blog.wxg630815指的是AndroidManifest.xml檔案中manifest元素的package屬性值。

 

使用demo:str給url賦值。

 

摘自 行在路上

聯繫我們

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