我正在尝试实施一个测验,用户从四个按钮中选择一个。当他们点击按钮时它会被选中,但是我想要做的是将之前选择的任何其他按钮重置为正常。这是我的类和代码,但它不会禁用其他按钮:
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()
方法。因为如果用户点击按钮然后改变主意并选择另一个按钮,那么应该禁用前一个按钮。点击按钮后我想转到下一个标签
答案 0 :(得分:1)
您可能想重新考虑整个设计。减少代码的方式更简单。尝试这样的事情:
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 ...
}
答案 1 :(得分:1)
如果我清楚地了解您的问题,如果您想要遵循您的第一个写入逻辑,那么当您单击button
为其设置黄色并且灰色为evryone exept clickt {{1 }}
button
但是有很多方法可以确保这一点。