我在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