Android自訂控制項的屬性配置

來源:互聯網
上載者:User

標籤:

        在Android的xml布局檔案裡,xmlns:android="http://schemas.android.com/apk/res/android",就是定義了xml的命名空間,以android開頭,比如:android:id="@+id/i_am"

        有時候,我們也想自訂命名空間。比如,在xmlns:android="http://schemas.android.com/apk/res/android"的下面寫上:xmlns:app="http://schemas.android.com/apk/res-auto"。以後就可以在整個xml布局檔案裡的控制項下面設定屬性,例如:app:me="@drawable/is_me"。但是,這個屬性必須在res/values/attrs.xml裡面聲明過:

1 <declare-styleable name="isme">2         <attr name="me" format="reference" />3 </declare-styleable>

        屬性設定好了,但是怎麼在java代碼裡面擷取到這些控制項的屬性呢。

 1 public CustomComponent(Context context, AttributeSet attrs) { 2     super(context, attrs); 3  4     TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CusComponent); 5  6     int imageSrcId; 7  8     try { 9          imageSrcId = a.getResourceId(R.styleable.isme_me,R.drawable.myimage);10 11     } finally {12          a.recycle();13     }14     LayoutInflater inflater = LayoutInflater.from(context);15 16     inflater.inflate(R.layout.custom_component_layout, this, true); // 給自訂控制項設定布局17     b = (ImageButton)findViewById(R.id.btn); // 擷取到布局上的ImageButton18     b.setImageResource(imageSrcId);19 20 }

        還有一點,就是命名空間的問題,就是res與res-auto的區別。通常我們在布局檔案中使用自訂屬性的時候 會這樣寫 xmlns:app=http://schemas.android.com/apk/res-auto,但如果你當前工程是做為lib使用,那麼你如上所寫 ,會出現找不到自訂屬性的錯誤 。 這時候你就必須 寫成 xmlns:app=http://schemas.android.com/apk/res/包名路徑。

       如果自訂屬性出現報錯的話,例如這樣的錯誤:Unexpected namespace prefix "app" found for tag fragment。解決方案:

到Eclipse的problems 標籤找到這個錯誤,右鍵然後選擇quick fix菜單,在彈出的菜單中選擇不檢查這個檔案(Disable check in this file only)就可以了。

 

        之前看了別人這麼多的文章,而自己又很懶,沒寫過文章。所以,這一次碰到了自訂屬性的配置問題,所以就把自己碰到的問題以及解決方案write下來,以供參考。第一次寫,勿噴。

 

Android自訂控制項的屬性配置

聯繫我們

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