【发布时间】:2016-06-27 17:38:52
【问题描述】:
我正在尝试实施一个测验,让用户从四个按钮中选择一个。当他们单击按钮时,它会被选中,但是我想做的是使之前选择的任何其他按钮重置为正常状态。这是我的课程和代码,但它不会禁用其他按钮:
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() 方法。因为如果用户点击一个按钮,然后改变主意并选择另一个按钮,那么前一个按钮应该被禁用。同样在单击按钮后,我想转到下一个选项卡
【问题讨论】:
-
在每个按钮的 else 中,您必须为每个按钮设置颜色
-
为什么不为每个按钮使用一个监听器。按下按钮时,保留对该按钮的引用。因此,在进一步的点击中,检查该 ref 是否不为空并相应地设置其状态。看到onClick方法中的那个View,就是被点击的按钮。
标签: java android android-fragments android-viewpager android-button