Reputation: 11829
I have a couple of buttons like
font1 = (Button)findViewById(R.id.fontsize1);
font2 = (Button)findViewById(R.id.fontsize2);
When I click on a button I want to change its textcolor and also change the textcolor of the rest of the buttons. Of course I do not want to write many lines best practice is a loop.
font1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
SaveFontSize("fontsize", "font1");
font1.setTextColor(Color.parseColor(color_active));
font1.setBackgroundResource(R.drawable.fonturesgreen);
}
}
});
I created a list:
List<String> fontarray = Arrays.asList("font1", "font2", "font3", "font4", "font5");
And in the loop I tried to do this:
for (int i=0; i<5; i++) {
fontarray.get(i).setTextColor(Color.parseColor(color_active));
}
This gives me an error, since fontarray.get(i) is a String, not a button.
Upvotes: 1
Views: 111
Reputation: 20394
you can actually iterate through controls in your layout, find buttons and compare their names (or other attributes you want) with the values stored in your List<String>
:
LinearLayout yourLayout = (LinearLayout) findViewById(R.layout.yourLayout);
for (int i = 0; i < yourLayout.getChildCount(); i++) {
Object block = yourLayout.getChildAt(i);
if (block instanceof Button) {
Button btn = (Button)block;
// do something with the button
}
}
Upvotes: 1
Reputation: 9368
You should do it this way:
List<Button> fontarray = Arrays.asList(font1, font2, font3, font4, font5);
Upvotes: 0
Reputation: 137322
Create a list of buttons as a class member instead:
List<Button> buttonArray = new ArrayList<Button>();
And in the onCreate()
:
buttonArray.add((Button)findViewById(R.id.fontsize1));
// same for the rest
now you can access it like that:
for (int i=0; i < buttonArray.length(); i++) {
buttonArray.get(i).setTextColor(Color.parseColor(color_active));
}
Upvotes: 0