到目前为止,我有以下代码允许我在单击组合在单选组中的切换按钮之间为文本视图设置一个值。出于某种原因,似乎 OnCheckedChanged 没有被调用。这是解决这个问题的方法吗?
//onClickListener method that returns an interface
private View.OnClickListener createClickListener(final int value) {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonValue = value;
buttonState = true;
ToggleButton clickedButton = (ToggleButton) view;
RadioGroup radioGroup= (RadioGroup) clickedButton.getParent();
final TextView num = (TextView) view.findViewById(R.id.num);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.number_zero:
buttonValue = value;
num.setText(buttonValue);
System.out.println("Button Value" + buttonValue);
case R.id.number_one:
buttonValue = value;
num.setText(buttonValue);
System.out.println("Button Value" + buttonValue);
case R.id.number_two:
buttonValue = value;
num.setText(buttonValue);
System.out.println("Button Value" + buttonValue);
case R.id.number_three:
buttonValue = value;
num.setText(buttonValue);
System.out.println("Button Value" + buttonValue);
}
System.out.println("Check changed listener called");
}
});
for (int i = 0; i < radioGroup.getChildCount(); ++i) {
View nextChild = radioGroup.getChildAt(i);
if (!(nextChild instanceof ToggleButton)) {
continue;
}
if (nextChild.getId() != clickedButton.getId() || !clickedButton.isChecked()) {
ToggleButton tb2 = (ToggleButton) nextChild;
tb2.setChecked(false);
}
}
}
};
}
调用使用:
zero.setOnClickListener(createClickListener(0));
one.setOnClickListener(createClickListener(1));
two.setOnClickListener(createClickListener(2));
three.setOnClickListener(createClickListener(3))
编辑:
由于某种原因,文本未设置为 num 的 TextView。
我从上面改变了
final TextView num = (TextView) view.findViewById(R.id.num);
num.setText(value);
至
num = (TextView) findViewById(R.id.num);
num.setText(Integer.toString(value));
这样做:
TextView num;
一个全局变量。
我使用了调试器,num 不为空,值为按钮的编号。