本文介绍了如何解决一个错误:getShared preferences(字符串,整数),该类型是未定义的新View.OnClickListener(){}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的编码得到这个错误,而不是完全知道如何解决这个问题。我已经搜查,试图解决这个问题,但似乎无法找到任何工作。我以前却从片段已经做到了这一点,所以也许这可能是因为这些?

I'm getting this error in my coding and not entirely sure how to resolve this. I've searched to try and resolve this issue but can't seem to find anything that works. I've done this before but never in a fragment so maybe it could be because of that?

我得到以下例外

该方法getShared preferences(字符串,INT)是未定义的类型新View.OnClickListener(){}

下面是我的code:

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

任何人都可以请帮助我吗?
任何帮助将AP preciated!

Could anyone please assist me with this?Any help will be appreciated!

推荐答案

更改此code:

SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);

要:

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

片段,记得直接你不能调用 getShared preferences 方法,因为它属于活动类。因此,你只需要调用 getActivity

Remember you cant call getSharedPreferences method directly from Fragment, because it belongs to the Activity class. Hence, you just need to call getActivity.

这篇关于如何解决一个错误:getShared preferences(字符串,整数),该类型是未定义的新View.OnClickListener(){}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 20:14