【发布时间】:2014-08-04 21:43:26
【问题描述】:
我是一名初学者,在尝试实现 SharedPreferences 以保存复选框的状态时遇到了一些问题。我一直在谷歌搜索一个答案,但没有运气。我无法理解要做什么,而且我的代码有一些问题。
我的 SuikodenFragment.java
的顶部public class SuikodenFragment extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener{
private final String TAG = getClass().getSimpleName();
public static final String suikodenprefs = "SuikodenPrefs" ;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.suikoden_main_activity1, container, false);
// you can use findViewById() using the above 'view'
// get the listview
expListView = (ExpandableListView) view.findViewById(R.id.suikodenList1);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
SharedPreferences settings = getSharedPreferences(suikodenprefs, 0);
boolean isChecked = settings.getBoolean("Tick the box", false);
setSilent(isChecked);
return view;
}
我在 getSharedPreferences 上遇到错误 - 它显示“方法 getSharedPreferences (String, int) 未定义 SuikodenFragment 类型”
在我的 SuikodenFragment.java
中进一步向下@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkbox_tick);
checkBox.setOnCheckedChangeListener(this);
if (isChecked)
// Add the tick to the box
Log.d(TAG, "Tick the box");
else
// Remove the tick in the box
Log.d(TAG, "Untick the box");
}
@Override
public void onStop(){
super.onStop();
// SharedPreferences sharedpreferences = getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
SharedPreferences settings = getSharedPreferences(suikodenprefs, 0);
settings.edit().putBoolean("Tick the box",true).commit();
}
上面的代码是复选框和保存复选框状态的代码,我希望。我再次在 getSharedPreferences 上遇到同样的错误。任何帮助都可以在这里做,因为我不太了解 SharedPreferences。提前致谢!
【问题讨论】:
-
@Jave 谢谢,我结合了 Irshad Khan 的建议,但我仍然不知道如何处理 setSilent...有什么想法吗?
标签: java android sharedpreferences