Java 更改按钮的颜色
我的应用程序有四个按钮。我试图让按钮的颜色改变为一种颜色,如果他们按一定的顺序,并让他们改变为不同的颜色,如果他们按不同的顺序。现在我的代码是:Java 更改按钮的颜色,java,android,button,colors,Java,Android,Button,Colors,我的应用程序有四个按钮。我试图让按钮的颜色改变为一种颜色,如果他们按一定的顺序,并让他们改变为不同的颜色,如果他们按不同的顺序。现在我的代码是: public class MainActivity extends Activity { int b1 = (int) (Math.random() * 10.0); int b2 = (int) (Math.random() * 10.0); int b3 = (int) (Math.random() * 10.0); int b4 = (int)
public class MainActivity extends Activity {
int b1 = (int) (Math.random() * 10.0);
int b2 = (int) (Math.random() * 10.0);
int b3 = (int) (Math.random() * 10.0);
int b4 = (int) (Math.random() * 10.0);
int last = 0;
int[] nums = { b1, b2, b3, b4 };
int i = 0;
String res = "";
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
private void checkOrder(int value) {
if (value == nums[i]) {
if (i == 3) {
//DO SOMETHING ELSE
} else {
if(value==b1){
button1.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}else if(value==b2){
button2.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}else if(value==b3){
button3.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}else if(value==b4){
button4.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}
i++;
}
} else {
//DO SOMETHING ELSE
}
}
现在我得到了一个NullPointerException,其中创建了按钮。我认为这是因为按钮不是在onCreate方法中创建的。但是,如果我将按钮放在onCreate方法中,则无法在checkOrder方法中访问它们。我该如何用不同的方法来改变它们的颜色?我知道过去也有人问过类似的问题,但我没有发现一个问题与我面临的问题相同。在类级别声明按钮,并在onCreate方法中初始化它们
Class Demo extends Activity{
Button button1,button2,button3,button4;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
}
}
使用完后,无论您想在何处使用这是您的完整编码?不。我有所有按钮的onClick方法,但我不认为它们对这个问题至关重要。