无重复随机图像

时间:2016-06-29 14:34:15

标签: android

我有一个随机图像显示器。但有时它会显示相同的图像。我想只显示1张图片......

                TypedArray ar = getResources().obtainTypedArray(R.array.arabalar);
            int len = ar.length();
            int[] resIds = new int[len];
            for (int i = 0; i < len; i++)
                resIds[i] = ar.getResourceId(i, 0);
            ar.recycle();

            Random rand = new Random();
            int rndInt = rand.nextInt(resIds.length) + 1;
            try {
                int resID = resIds[rndInt];
                ImageView logolar = (ImageView)findViewById(R.id.logolar);
                logolar.setImageResource(resID);
                lastImageName = getResources().getResourceEntryName(resID); //String lastImageName = getResources().getResourceName(resID); // bu da kullanilabilir
                TextView logoismi = (TextView)findViewById(R.id.logoismi);
                logoismi.setText(previousImageName);
                clickeddata.add(logoismi.getText().toString()); //bir onceki logo verilerini depolama ozelligi
            } catch (Exception e) {
                e.printStackTrace();
            }

            previousImageName = lastImageName;

1 个答案:

答案 0 :(得分:0)

随机播放资源ID数组并将其用作支持列表。

        private int[] resIds;

        private int index;

一开始就这样做一次:

        TypedArray ar = getResources().obtainTypedArray(R.array.arabalar);
        int len = ar.length();
        resIds = new int[len];
        for (int i = 0; i < len; i++)
            resIds[i] = ar.getResourceId(i, 0);
        ar.recycle();

        // shuffle
        // loop backwards through the array and swap each item 
        // with a random item from the values below it
        Random random = new Random();
        for (int i = resIds.length - 1; i > 0; i--) {
            int index = random.nextInt(i + 1);
            // swap
            int temp = resIds[i];
            resIds[i] = resIds[index];
            resIds[index] = temp;
        }

现在只需单步执行您的数组:

        try {
            int resID = resIds[index];
            ImageView logolar = (ImageView)findViewById(R.id.logolar);
            logolar.setImageResource(resID);
            lastImageName = getResources().getResourceEntryName(resID); //String lastImageName = getResources().getResourceName(resID); // bu da kullanilabilir
            TextView logoismi = (TextView)findViewById(R.id.logoismi);
            logoismi.setText(previousImageName);
            clickeddata.add(logoismi.getText().toString()); //bir onceki logo verilerini depolama ozelligi
        } catch (Exception e) {
            e.printStackTrace();
        }

        previousImageName = lastImageName;
        index++;