我正在尝试在Fragment类中接收复选框选项,但是我无法使用我在Activities中使用的方式(从android:onClick="onCheckboxClicked"
调用layout.xml
方法),因为每次调用此方法时,我都会得到“找不到onCheckboxClicked的方法”。
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();
}
所以,我已经实现了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;
}
}
答案 0 :(得分:3)
@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;
}
checkboxvariable.setOnClickListener(this.getActivity());
在onClick中你可以获得资源ID,R.id.checkboxid。
答案 1 :(得分:2)
任何onClick
XML属性都意味着必须在活动中找到该方法,而不是在片段中,而不是在视图中。所以我看到它的方式,你有两个选择:
onClick
并依赖您在Java代码中定义的OnClickListeners
。该主题已在at least this thread中讨论过。答案 2 :(得分:0)
只需使用自定义监听器
即可CompoundButton.OnCheckedChangeListener
在任何其他视图中,然后活动。代码示例
public class MyFragment extends Fragment{
public View onCreateView(...){
...
CheckBox cbFilter = (CheckBox) rootView.findViewById(R.id.chb_rt_is_filter);
cbFilter.setOnCheckedChangeListener(myCheckboxListener);
return rootView;
}
private CompoundButton.OnCheckedChangeListener myCheckboxListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()){
case R.id.chb_rt_is_filter:
break;
default:
break;
}
}
};
}
答案 3 :(得分:0)
public class MyFragment extends Fragment {
CheckBox myCheckBox;
@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle saveInstanceState) {
rootView = layoutInflater.inflate(R.layout.your_fragment_layout, container, false);
...
...
initViews();
return rootView;
}
private void initViews() {
myCheckBox = (CheckBox) rootView.findViewById(R.id.my_check_box);
myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked)
Log.d("TAG=>isChecked", "True");//replace your own stuffs here
else
Log.d("TAG=>isChecked", "false");//replace your own stuffs here
}
});
}
}
您可以为n个复选框设置此侦听器!!!