N
N
Nikita Avdeev2017-03-04 15:08:39
Java
Nikita Avdeev, 2017-03-04 15:08:39

How to make one variable for several buttons?

Good day!
We have 22 buttons in 1 layout1 . When you press any of these buttons, the same Activity2 and the layout2 attached to it will be activated . But depending on the pressed button in layout1 , the content of the text in layout2 will change . And now, dear experts, a question. How not to prescribe the action of each button, but simply make the OnClickListener listen for any click and and perform a specific action? It's just that if everything is templated, I doubt that the developer will code each button, which will only differ in id and text that will be displayed in layout2 .
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Gamega, 2017-03-04
@Ozymandias249

for(int i=0; i < layout.getChildCount(); i++){
    View v = layout.getChildAt(i);
    if (v instanceof Button) {
        Button button = (Button) v;
        button.setOnClickListener(this);
    }
}

R
Rou1997, 2017-03-04
@Rou1997

I doubt that the developer will code each button, which will only differ in id and text

But in Layout it was "coded", and what's the problem with copying "findViewById" 22 times and what else is there? If this shocks him, then he would write a plugin for the IDE to automatically generate this "findViewById", a long time ago, in all normal GUIs this is automated, only in Android everything is stupid, but developers from Microsoft who created VB 6.0, in they would be shocked to learn that twenty years later there will be a platform where this is still not the case, and it is one of the most popular.
And you can create an array or list of IDs, and then a loop, there will be less "copy-paste" and more flexibility.
Although, probably, it was worth initially using the software creation of buttons, in a loop, and each set the same OnClickListener.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question