Android SharedPreferences from onclick in a fragment



我希望有人能给我一些关于如何从onViewCreated事件中定义的按钮的onclick事件中访问SharedPreferences的方向。

我可以在onViewCreated事件中设置接口的值,通过调用:

SharedPreferences prefs = this.getActivity().getSharedPreferences(
    "com.example.app", Context.MODE_PRIVATE);

,并获得适当的值,但我有一个按钮在界面上按下保存更改,我似乎不能想出正确的方法来访问sharepreferences从我的按钮的单击事件:

Button btn = (Button)view.findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
        Log.d("test","here");
        SharedPreferences prefs = this.getActivity().getSharedPreferences(
                "com.example.app", Context.MODE_PRIVATE);
    }
});

这段代码显然不工作,因为这里这是引用视图和getActivity不能从视图工作。谁能告诉我如何从这里访问活动,这样我就可以访问共享偏好?

大家好,欢迎来到StackOverflow。

你不能访问SharedPreferences的原因是因为this不是片段:如果你仔细看,你会意识到你有2 嵌套上下文,所以this真的是一个OnClickListener对象(在你的片段内)。

当您需要访问"父上下文"时,您可以这样做:

 public class MyCoolFragment extends Fragment {
    // here "this" is in fact your Fragment,
    // so this.getActivity().getSharedPreferences() DOES exist
    .
    .
    .
    Button btn = (Button)findViewById(R.id.btnSave);
    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            // "this" is NO LONGER your fragment, but the View.OnClickListener
            // to access the PARENT CONTEXT you prepend the CLASS NAME:
            // MyCoolFragment.this.getActivity().getSharedPreferences will work:

            SharedPreferences prefs = MyCoolFragment.this.getActivity().getSharedPreferences()
                    "com.example.app", Context.MODE_PRIVATE);
        }
    });

在Java中有非常典型的深度嵌套上下文,所以你必须告诉Java你想要什么this

另外,请记住,您可以轻松地从任何视图获取上下文。,所以在click处理程序中你也可以这样做:

        Button btn = (Button)view.findViewById(R.id.btnSave);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                Activity myActivity=(Activity)(v.getContext()); // all views have a reference to their context
                SharedPreferences prefs =myActivity.getSharedPreferences(
                        "com.example.app", Context.MODE_PRIVATE);
            }
        });

兄弟,这很简单。看看我的代码片段。你会明白怎么做的

   SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
   return sharedPreferences.getString(key, "");

您是否尝试过使用getActivity().getSharedPreferences()?

SharedPreferences prefs = getActivity().getSharedPreferences(
            "com.example.app", Context.MODE_PRIVATE);

注意:由于我的声誉很低,所以不能把这个作为问题来问。

最新更新