Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

view - android: how to elegantly set many button IDs

I have many buttons in my activity (only a subset of which are visible at a time). I currently have something ugly like this:

buttonID[0] = R.id.buttonr1b1;
buttonID[1] = R.id.buttonr1b2;
buttonID[2] = R.id.buttonr1b3;
buttonID[3] = R.id.buttonr1b4;
...
buttonID[35] = R.id.buttonr1b36;

for (int i = 0; i < 36; i++) {
    button[i] = (Button) findViewById(buttonID[i]);
}

Is there a more elegant way to reference all of R.id.buttonXXX ? It just looks so wrong and ugly. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your instincts are correct. It's ugly and in general if you find yourself wanting to do this you should rethink your design.

If your buttons are uniform to the point where you want to loop over them to do something like this, they're probably uniform enough to generate programmatically in the first place (and you can store references as you create them) or use some form of AdapterView. What data needs to be associated with each button? Can you associate it directly using setTag/getTag? Do you need to use IDs here at all?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...