如何使操作调用一次

如何使操作调用一次

本文介绍了如何使操作调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有无限的viewpager每个已着色。
因此,对应用程序的关闭操作再次被调用,但我想的是下一次启动该操作不应该再次调用

Let's say i have unlimited viewpager and each have been colored.So on close of the app the operation again being called but what i want is for next start up that operation should not be called again

推荐答案

根据您的问题,这种讨论和项目链接,就尝试了这一点:

Based on your question, this discussion and the project link, just try this out:

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 设置,您可以使用加载图像:

Assuming you have the ImageView set up in myfragment_layout, you can load the image using:

&LT; ImageView的&GT; .setImageResource(resourceImageID);

这篇关于如何使操作调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:24