请帮助我在我的 activity_main.xml 文件中的布局中有许多带有文本和图像的按钮。
<Button
android:drawableTop="@drawable/ring"
android:id="@+id/Button1"
android:text="pic1" />
其他每个按钮都有不同的@drawable 资源、id 和文本。
问题:我如何以编程方式循环遍历 MainActivity.java 中的每个按钮并获取 @drawableTop 属性的值,因此在上述情况下 - ring
最佳答案
首先,您需要知道有多少 child 拥有您正在使用的 LinearLayout 或 RelativeLayout。然后,创建一个循环来获取每个 child 。最后,验证 View 类型并获取可绘制顶部。
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
}
}
关于java - 获取按钮android java的xml属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730578/