片段内的复选框 - 捕获选中/取消选中

Kri*_*her 3 checkbox android android-fragments

我试图在 Fragment 类中接收复选框选择,但是我无法使用在 Activity 中使用的方式(android:onClick="onCheckboxClicked"从 a 调用方法layout.xml),因为每次使用此方法时我都会收到“method onCheckboxClicked not found”叫。

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

    // Check which checkbox was clicked
    switch(view.getId()) {
        case (R.id.checkBox_wifi):
            if (checked)    {
                editor.putBoolean("wifi_on_off", true);
            }
            else    {
                editor.putBoolean("wifi_on_off", false);
            }
            break;

    }

    editor.apply();
}
Run Code Online (Sandbox Code Playgroud)

所以,我已经实现了 View.OnClickListener,但这没有得到任何复选框检查/取消选中:

 @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.checkBox_wifi:
            boolean checked = ((CheckBox) view).isChecked();

            if (checked) {
                editor.putBoolean("wifi_on_off", true);
            } else {
                editor.putBoolean("wifi_on_off", false);
            }

            editor.apply();
            break;

    }
}  
Run Code Online (Sandbox Code Playgroud)

ind*_*gga 5

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragmentlayout, container,false);

    CheckBox checkboxvariable=(CheckBox)rootView.findViewById(R.id.checkboxid);

    checkboxvariable.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


            if(v.isChecked()){ //do this}
            else { //do this }

        }
    });
    return rootView;
}
Run Code Online (Sandbox Code Playgroud)

checkboxvariable.setOnClickListener(this.getActivity());

在onClick里面你可以得到资源id,R.id.checkbodi。