the_big_blackbox
the_big_blackbox

Reputation: 1196

get xml attribute of button android java

Please help I have the a number of buttons with text and images in a layout in my activity_main.xml file.

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

Each of the other buttons have a different @drawable resource, id and text.

Question: How would I programmatically loop through each of the buttons in MainActivity.java and obtain the value of the @drawableTop attribute, so in the above case - ring

Upvotes: 1

Views: 509

Answers (2)

jmarkstar
jmarkstar

Reputation: 1335

Firstly you need to know how many children have the LinearLayout or RelativeLayout that you are using. Then, create a loop to get each child. Finally, validate the type of the view and get the drawable top.

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

Upvotes: 1

adalpari
adalpari

Reputation: 3121

From documentation:

Drawable[] getCompoundDrawables ()

Returns drawables for the left, top, right, and bottom borders.

So

button.getCompoundDrawables()[1];

will return drawable for top.

Upvotes: 0

Related Questions