开发者

Possible to change color of a button outside the activity class?

I have an activity with a layout and some buttons in it, I want to change color of those buttons. But there are lot more buttons so I want to change开发者_如何学Python them using a method defined in other class. Is this possible? I tried by creating a new class which extends the current class. But it is getting force closed.

public class Color_change extends Calculate
{
    public  void test()
    {
        Button button = (Button)findViewById(R.id.one);
        button.setTextColor(0xFFFF0000);
    }
}

Calculate is a main class which extends Activity. And I'm calling as below:

Color_change a = new Color_change();
a.test();


If the current Activity being displayed on the screen isn't Color_change the code you wrote will not function. If you want to have a separate class that changes the color of a set of buttons, I would suggest passing the buttons in some form of collection to the class that changes the button color. You could write a class like this:

public class ColorChanger
{
  public void changeColor(Collection<Button> buttons)
  {
    for(Button b : buttons) {
       changeButtonColor(b);
    }
  }

  private void changeButtonColor(Button button) {
       switch(button.getId()) {
           case R.id.one:
                button.setTextColor(0xFFFF0000); 
                break;
           default: 
                // set default color?
                break;
       }
  }
}

Then you would just need to make a list of all the buttons you need to pass to your color changer.

List<Button> buttons = new ArrayList<Button>();
buttons.add((Button)findViewById(R.id.one));
//add any more buttons

Just be aware, that theming and styling in Android allows you to accomplish a great deal of these kinds of effects. I would be sure you exhausted your efforts there before turning to a code solution.


Pass the buttons to the test method or the Context to the constructor class and then you could change the color. Like in

public class ColorChange extends Calculate {
   public static void test(Button button) {
      button.setTextColor(0xFFFF0000);
   }
}

Also note the change in the class name to follow the conventions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜