2015-12-15 103 views
5

我見過很多人想知道如何獲得自定義組件的自定義屬性,但這不是我的問題。我創建了一個自定義組件,我試圖添加屬性,但是當我在我的xml文件的頂部添加名稱空間時,它只發現兩個隨機自定義屬性「paddingEnd」和「paddingStart」。Android自定義屬性不顯示

<resources> 
    <declare-styleable name="menu_item_attrs"> 
     <attr name="imageId" format="integer" /> 
     <attr name="menuText" format="string" /> 
    </declare-styleable> 
</resources> 

這是attrs.xml文件。

public MenuListItem(Context context, AttributeSet set) { 
    super(context, set); 

    TypedArray a = context.obtainStyledAttributes(set, R.styleable.menu_item_attrs); 
    if (a == null) { 
     return; 
    } 
    CharSequence s = a.getString(R.styleable.menu_item_attrs_menuText); 
    if (s != null) { 
     // do something 
    } 
} 

這是我的自定義類的構造函數。

 <LinearLayout 
      xmlns:custom="http://schemas.android.com/apk/res-auto" 
      android:layout_width="match_parent" 
      android:layout_height="0dp" 
      android:id="@+id/expanding_layout" 
      android:background="#029eed"> 

      <aaron.testappanim.MenuListItem 
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content"/> 
     </LinearLayout> 

這是我使用的組件。我想將值添加到「imageId」和「menuText」,但它們不可用。唯一顯示的內容是填充相關,如下所示。

enter image description here

任何想法的傢伙?

回答

12

找到解決方案。

碰巧你需要將風格化的名稱與你的類名稱相同。

<resources> 
    <declare-styleable name="MenuListItem"> 
     <attr name="my_custom_attribute" format="integer" /> 
    </declare-styleable> 
</resources> 

在這種情況下很多很多帖子都是錯誤的,因爲我可以看到很多樣式名稱完全不同。

希望這可以阻止別人陷入這個陷阱。

乾杯

+0

幫我在網上淘的答案,這個簡單的問題後,極大地。謝謝! – chaser

-1

我的解決辦法: 在attr.xml文件,你可能已經宣告您的自定義屬性如下

<declare-styleable name="IDEditText"> <attr name="customFont" format="string"/> </declare-styleable>

這裏,declare-styleable name字段必須是名自定義視圖。然後它會顯示在建議中。

在mycase我的自定義視圖名稱爲IDEditText,因此declare-styleable NAME =「IDEditText」

+1

這是正確的..但它已經被回答!不管怎麼說,還是要謝謝你! – Murphybro2

+0

歡迎您。我只是有這個問題,所以認爲它可能會幫助別人 – Vishnu