android - onClick 在 fragment 内部不起作用

标签 android android-fragments onclicklistener

出于某种原因,onclick 监听器没有响应以下 fragment 中的点击事件,您知道为什么吗?

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);

    }

最佳答案

RadioGroup 上使用 OnCheckedChangeListener,而不是 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

关于android - onClick 在 fragment 内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400230/

相关文章:

java - 使用 onTouchListener 旋转图像而不缩放图像

android - 可以使用每次返回新 LiveData 的存储库功能从 UI 刷新 LiveData?

android - fragment 中的 getActivity() 与 this.getActivity()

android - 通过监听器检查 EditText 是否为空

android - 将 onClickListener 设置为由自定义适配器填充的 LinearLayout

android - PhoneGap 中的视频缩略图?

java - 保存临时数组列表以在适配器中使用

java - 当 fragment 膨胀时,抽屉导航启动未知 Activity

android - onSaveInstanceState 在 onDestroyView 之后调用

java - 按下时按钮没有反应