如何在 FragmentStatePagerAdapter 中获取 SharedPreference 对象? [英] How do I get SharedPreference object in FragmentStatePagerAdapter?

查看:56
本文介绍了如何在 FragmentStatePagerAdapter 中获取 SharedPreference 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在自定义寻呼机适配器的 getCount() 方法中动态添加一个整数,该方法显然扩展了 FragmentStatePagerAdapter.

I wanna add an integer dynamically in the getCount() method of custom pager adapter that obviously extends FragmentStatePagerAdapter.

return some integer value;

我在 Shared Preference 对象中保存了一个计数器,它会通过点击星形图像进行更新.我想在提到的方法中返回更新的计数器值,所以我可以生成很多滑动视图,但问题是我无法在那里获取共享首选项对象.这是我的应用程序和 Play 商店之间的唯一障碍,我已经开发它大约一两个月了.所以请就我面临的这个问题给我建议.在此先感谢各位!

I have a counter saved in Shared Preference object and it gets updated with clicks on star images. I wanna return the updated counter value in the mentioned method, so I can generate that many swipe views but the problem is I unable to get Shared Preference object there. This is the only obstacle between my app and the play store, I've been developing it for like month or two. So please gimme suggestion on this issue I'm facing. Thanks in advance guys!

推荐答案

https://developer.android.com/training/basics/data-storage/shared-preferences.html

https://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int)

设置您的 value onPause() 和 onStop 并读取您的 value onResume 和 onCreate.

Set your value onPause() and onStop and read your value onResume and onCreate.

您需要设置一个最终字符串,这将是您的 SharedPreferences 文件名.

You need to set a final string which would be your SharedPreferences filename.

获取你的价值并增加

写作:

SharedPreferences sharedPref = getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_value), newValue);
editor.commit();

阅读:

SharedPreferences sharedPref = getActivity().getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_value_default);
long value = sharedPref.getInt(getString(R.string.saved_value), defaultValue);

首先读取值并将其设置为共享首选项中的变量.

First read the value and set it to a variable in shared preferences.

增加相同的值 onPause 或 onStop.

Increment the same value onPause or onStop.

这篇关于如何在 FragmentStatePagerAdapter 中获取 SharedPreference 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆