让我们说我有无限的viewpager,每个都有颜色。 因此,在应用程序关闭时,操作再次被调用,但我想要的是下次启动时不应该再次调用该操作
答案 0 :(得分:0)
在该操作之后,您应该使用SharedPreferences存储布尔“firstTime”。在循环之前恢复该值并更改图像数组。
答案 1 :(得分:0)
这是您设置共享偏好的方式:
SharedPreferences preferences = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("page" + mCurrentPage, randInt);
editor.commit();
要检索它们,您需要执行以下操作:
int randInt = preferences.getInt("page" + mCurrentPage, -1);
代码:
SharedPreferences preferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
int randInt = preferences.getInt("page" + mCurrentPage, -1);
if(randInt == -1) {
randInt = new Random().nextInt((8));
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("page" + mCurrentPage, randInt);
editor.commit();
}
答案 2 :(得分:0)
根据您的问题,此讨论和project链接,只需尝试一下:
在MainActivity
中添加这两个全局变量:
/**
* {@link SharedPreferences} key for the random int array.
*/
public static final String KEY_RANDOM_INT_FOR_INDEX = "random_int_index";
/**
* Value holding the total number of images.
*/
public static final int TOTAL_IMAGES = 8;
然后在onCreate
MainActivity
的末尾再次添加:
// Get a reference to the default SharedPreferences
SharedPreferences defSharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
// Check if there is a random int for at least 1 index
if (defSharedPreference.getInt(KEY_RANDOM_INT_FOR_INDEX + "_0", -1) == -1) {
// Generate array of <TOTAL_IMAGES> random ints;
ArrayList<Integer> allInts = new ArrayList<Integer>();
for (int i = 0; i < TOTAL_IMAGES; i++) {
allInts.add(i);
}
// Editor instance for modifying SharedPreferences;
SharedPreferences.Editor sp_editor = defSharedPreference.edit();
// Generate random ints;
for (int i = 0; i < TOTAL_IMAGES; i++) {
int range = allInts.size();
int pickIndex = (int) (Math.random() * range);
int value = allInts.remove(pickIndex);
// System.out.print("\nindex: " + i + "\t=\t" + value);
// Save the random value with the key;
sp_editor.putInt(KEY_RANDOM_INT_FOR_INDEX + "_" + i, value);
}
// Save the editors queue in the SharedPreferences;
sp_editor.commit();
}
最后在onCreateView
MyFragment
添加:
// Get a reference to the default SharedPreferences
SharedPreferences defSharedPreference = PreferenceManager
.getDefaultSharedPreferences(getActivity());
// Calculate the index of the page from base of TOTAL_IMAGES;
int pageIndexInTotalImages = (mCurrentPage - 1)
% MainActivity.TOTAL_IMAGES;
// Calculate the index of the random image for the page;
int imageID = defSharedPreference.getInt(
MainActivity.KEY_RANDOM_INT_FOR_INDEX + "_"
+ pageIndexInTotalImages, 0);
int resourceImageID = imageID + R.drawable.image0;
假设您在ImageView
中设置了myfragment_layout
,则可以使用以下方式加载图片:
<ImageView>.setImageResource(resourceImageID);