我正在尝试实现一个测验,用户可以从四个按钮中选择一个。当他们点击按钮时,它会被选中,但我想做的是让之前选择的任何其他按钮重置为正常。这是我的类和代码,但它不会禁用其他按钮:
public class QuizOne extends Fragment{
Button one;
Button two;
Button three;
Button four;
boolean selected = false;
public QuizOne(){
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quiz, container, false);
one = (Button) rootView.findViewById(R.id.ones);
two = (Button) rootView.findViewById(R.id.twos);
three = (Button) rootView.findViewById(R.id.threes);
four = (Button) rootView.findViewById(R.id.fours);
selectedButton();
return rootView;
}
public void selectedButton(){
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected){
one.setBackgroundColor(Color.YELLOW);
}
else {
one.setBackgroundColor(Color.GRAY);
selected = true;
}
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected){
two.setBackgroundColor(Color.YELLOW);
}
else {
two.setBackgroundColor(Color.GRAY);
selected = true;
}
}
});
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected){
three.setBackgroundColor(Color.YELLOW);
}
else {
three.setBackgroundColor(Color.GRAY);
selected = true;
}
}
});
four.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected){
four.setBackgroundColor(Color.YELLOW);
}
else {
four.setBackgroundColor(Color.GRAY);
selected = true;
}
}
});
}
}
所以它是我正在努力研究的 selectedButton()
方法。因为如果用户点击一个按钮然后改变主意并选择另一个按钮,那么应该禁用前一个按钮。同样在单击按钮后我想转到下一个选项卡
最佳答案
您可能需要重新考虑您的整个设计。有更少的代码更简单的方法。尝试这样的事情:
public class QuizOne extends Fragment implements View.OnClickListener {
....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quiz, container, false);
one = (Button) rootView.findViewById(R.id.ones);
one.setOnClickListener(this);
// and so on ...
@Override
public void onClick(View v) {
setButtonsGray();
v.setBackgroundColor(COLOR.Yellow);
}
private void setButtonsGray(){
one.setBackgroundColor(COLOR.Gray);
two.setBackgroundColor(COLOR.Gray);
// and so on ...
}
关于java - 单击时如何只选择一个按钮 -QUIZ ANDROID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35957789/