1

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.

3 Answers 3

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

You should do it this way:

List<Button> fontarray = Arrays.asList(font1, font2, font3, font4, font5);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.