gpt4 book ai didi

android - 如何解决错误 : getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:27 25 4
gpt4 key购买 nike

我在编码时遇到了这个错误,但不确定如何解决这个问题。我进行了搜索以尝试解决此问题,但似乎找不到任何有效的方法。我以前做过,但从来没有在 fragment 中做过,所以可能是因为那个?

我遇到了以下异常:

The method getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}

这是我的代码:

public class TestingFragment extends Fragment {

public TestingFragment(){}
private CheckBox ch;
private Context pref;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_testing, container, false);

ch = (CheckBox) rootView.findViewById(R.id.checkBox62);
ch.setOnClickListener(new View.OnClickListener() {
private String PREFRENCES_NAME;

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(ch.isChecked())
{
SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);
ch.setChecked(pref.getBoolean("cbx62_ischecked" ,true));
pref.edit().putBoolean("check",false).commit();
}
{
}}
});
return rootView;
} }

有人可以帮我解决这个问题吗?任何帮助将不胜感激!

最佳答案

更改此代码:

SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);

收件人:

SharedPreferences pref = getActivity().getSharedPreferences(PREFRENCES_NAME,0);

请记住,您不能直接从 Fragment 调用 getSharedPreferences 方法,因为它属于 Activity 类。因此,您只需调用 getActivity

关于android - 如何解决错误 : getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26779850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com