2016-06-09 60 views
1

請幫助我有我的activity_main.xml文件中的佈局中的文本和圖像的按鈕數量。得到xml屬性的按鈕android java

<Button 
    android:drawableTop="@drawable/ring" 
    android:id="@+id/Button1" 
    android:text="pic1" /> 

其他每個按鈕都有不同的@drawable資源,id和文本。

問題:如何將我通過每個在MainActivity.java按鈕並獲得@drawableTop屬性的值編程循環,所以在上述的情況下 - 環

回答

0

從文檔:

Drawable [] getCompoundDrawables()

返回左,上,右,下邊框的drawables。

所以

button.getCompoundDrawables()[1]; 

將返回繪製頂級。

1

首先,您需要知道您有多少個孩子使用了LinearLayout或RelativeLayout。然後,創建一個循環來獲取每個孩子。最後,驗證視圖的類型並獲取可繪製的頂部。

LinearLayout layout = setupLayout(); 
int count = layout.getChildCount(); 
View view = null; 
for(int i=0; i<count; i++) { 
    view = layout.getChildAt(i); 
    if (view instanceof Button) { 
     Button myButton = (Button) view; 
     Drawable drawableTop = myButton.getCompoundDrawables()[1]; 
     //YOUR CODE 
    } 
}