Ian Gallegos
Ian Gallegos

Reputation: 558

Other way to set a dimension of ImageButton

I am working with ImageButton in Android studio and during the development of the code I need to change the dimension of my ImageButtons.

I fuond in a previous question a part of solution.

stackoverflow.com/questions/10992241/set-imagebutton-height-and-width-in-code

android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;
    button1.setLayoutParams(params1);
android.view.ViewGroup.LayoutParams params2 = button2.getLayoutParams();
    params2.height = size;
    params2.width = size;
    button2.setLayoutParams(params2);
android.view.ViewGroup.LayoutParams params3 = button3.getLayoutParams();
    params3.height = size;
    params3.width = size;
    button3.setLayoutParams(params3);

Is there an other way to manage ImageButtons without repeat the follow code for all?

android.view.ViewGroup.LayoutParams params1 = button1.getLayoutParams();
    params1.height = size;
    params1.width = size;

Upvotes: 0

Views: 48

Answers (1)

Debashis Choudhury
Debashis Choudhury

Reputation: 3392

You could name your buttons in layout in a sequential way (you may change them according to screen name, action name as you wish)

Like : button_1, button_2, button_3 etc.

You could get list of such button this way:

List<ImageButton> toBeResizedButtons() {

    ArrayList<ImageButton> buttons = new ArrayList<>();

    for (int i = 1; i <= NUMBER_OF_BUTTONS ; i++) {
        int id = getResources().getIdentifier("button_" + i, "id", getPackageName());
        buttons.add((ImageButton) findViewById(id));
    }

    return buttons;
}

You could resize all of those in a single statement like this

for(ImageButton b : toBeResizedButtons()) {

     resize(b, size);
}

Where resize() assumes you have a fixed size to resize them.

void resize(View v, int size) {

    android.view.ViewGroup.LayoutParams params = v.getLayoutParams();
    params.height = size;
    params.width = size;
}

Upvotes: 1

Related Questions