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 
    } 
}