我在android开发中的新功能。 我想通过Android中的java编码更改我的按钮背景。更改按钮背景颜色使用if-else在android中
我想,当我点击按钮,它变成黄色和白色(包括男女按钮),点击后单击是。
我在android开发中的新功能。 我想通过Android中的java编码更改我的按钮背景。更改按钮背景颜色使用if-else在android中
我想,当我点击按钮,它变成黄色和白色(包括男女按钮),点击后单击是。
首先您需要绑定您的按钮在活动这样
btnMale=(Button) findViewById(R.id.btnMale);
btnFemale=(Button) findViewById(R.id.btnFemale);
比我们的按钮setOnClickListener()
这样
btnMale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//btnMale.setBackgroundResource(R.drawable.background);// change background your button like this
btnMale.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorPrimary));// use this to set color as background
btnFemale.setBackgroundResource(android.R.drawable.btn_default;);// use this to set color as background
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnFemale.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorPrimary));// use this to set color as background
btnMale.setBackgroundResource(android.R.drawable.btn_default;);// use this to set color as background
}
});
Button11.setBackgroundColor(getResources().getColor(R.color.red));
//或者,如果你不是:
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));
或者,alterna tively:
Button11.setBackgroundColor(Color.RED);
//从android.graphics.Color 或者,更加有利于技能:
Button11.setBackgroundColor(0xFFFF0000);
// 0xAARRGGBB
你可以做这样的事情:
@Override
public void onCreate(Bundle savedInstanceState) {
Button buttonMale = (Button) findViewById(R.id.btn_male);
Button buttonFemale = (Button) findViewById(R.id.btn_female);
buttonMale.setOnClickListener(getGenderOnClickListener(buttonFemale));
buttonFemale.setOnClickListener(getGenderOnClickListener(buttonMale));
}
private Consumer<View> getGenderOnClickListener(View other) {
return view -> {
view.setBackgroundColor(Color.YELLOW);
other.setBackgroundColor(Color.WHITE);
}
}
添加乌尔代码你到目前为止尝试 – Anil
https://stackoverflow.com/questions/14023886/android-button-selector这可能会帮助你。 –
可能重复的[android程序设置按钮后台](https://stackoverflow.com/questions/13842447/android-set-button-background-programmatically) – anonymous