由于某种原因,onclick监听器没有响应以下片段中的点击事件,为什么会有任何想法?
public class TestFragment extends Fragment{
private TextView textViewOne;
private RadioButton radioButtonOne;
private RadioButton radioButtonTwo;
private RadioButton radioButtonThree;
private Spinner spinnerOne;
private RadioGroup radioGroupOne;
String buttonSelected;
Activity activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
activity = getActivity();
View result=inflater.inflate(R.layout.tank_layout7, container, false);
textViewOne = (TextView) result.findViewById(R.id.textView1);
ratioButtonOne = (RadioButton) result.findViewById(R.id.radioButton1);
ratioButtonTwo = (RadioButton) result.findViewById(R.id.radioButton2);
ratioButtonThree = (RadioButton) result.findViewById(R.id.radioButton3);
spinnerOne = (Spinner) result.findViewById(R.id.spinner1);
radioGroupOne = (RadioGroup) result.findViewById(R.id.radio_group1);
radioGroupOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int checkedRadioButton = radioGroupOne.getCheckedRadioButtonId();
switch(checkedRadioButton){
case R.id.radioButton1:
buttonSelected = "button one selected";
break;
case R.id.radioButton2:
buttonSelected = "button two selected";
break;
case R.id.radioButton3:
buttonSelected = "button three selected";
break;
default:
}
Toast.makeText(activity, "radio button selected " + buttonSelected, Toast.LENGTH_SHORT).show();
}
});
return(result);
}
}
答案 0 :(得分:4)
使用OnCheckedChangeListener
上的RadioGroup
,而不是OnClickListener
:
radioGroupOne.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
// Your code
}
}
});
http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html