在图像视图中随机化图像

时间:2013-12-30 11:26:15

标签: android

我想制作一个应用程序,其中我必须randomaly生成图像,但按顺序....

喜欢: - APPLE ....我想将其生成为A_PP_E .... 但我也希望他们每次都能获得独特的

final int[] imageViews = {
        R.id.imageView2, R.id.imageView10, R.id.imageView3, 
        R.id.imageView4, R.id.imageView5, R.id.imageView6, R.id.imageView8  };
int[] photos={R.drawable.aa, R.drawable.pp
        ,R.drawable.ee,
        R.drawable.pp_blue,R.drawable.ll};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // for randomizing the view
     Random rng = new Random(); 
     List<Integer> generated = new ArrayList<Integer>();
     for (int i = 0; i < 5; i++)
     {
       while(true)
       {
          Integer next = rng.nextInt(5) ;
          if (!generated.contains(next))
          {
             generated.add(next);
             ImageView iv = (ImageView)findViewById(imageViews[i]);
             iv.setImageResource(photos[next]);
             break;
          }
        }
     }

2 个答案:

答案 0 :(得分:1)

步骤1):按正确顺序将图像放入数组中,如下所示:

int[] photos={R.drawable.aa, R.drawable.pp, R.drawable.pp_blue, R.drawable.ll, R.drawable.ee}; // correct order APPLE

步骤2):更新您的代码,如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Random rng = new Random();
    List<Integer> generated = new ArrayList<Integer>();

    // select `n` places which will be "BLANK"
    int n = 2; // example `n=2`
    for (int i = 0; i < n; i++)
    {
        while(true)
        {
            Integer next = rng.nextInt(5) ;
            if (!generated.contains(next))
            {
                generated.add(next);
                break;
            }
        }
    }

    // now `generated` has `n` random positions
    // set these `n` positions as "BLANK" rest as "FILLED"
    for (int i = 0; i < 5; i++)
    {
        ImageView iv = (ImageView)findViewById(imageViews[i]);
        if(generated.contains(i)) {
            // this was a random selected position
            // set it blank or empty
            iv.setImageBitmap(null);
        }
        else {
            // set this image as the correct alphabet
            iv.setImageResource(photos[i]);
        }
    }

}

答案 1 :(得分:0)

我这样做是为了在另一个图像视图数组中获取空​​白图像....并给出正确的输出

int n = 2; // example `n=2`
    for (int i = 0; i < n; i++)
    {
        while(true)
        {
            Integer next = rng.nextInt(5) ;
            Log.i("test","value:-"+next);               
            if (!generated.contains(next))
            {
                generated.add(next);
                break;
            }

        }
    }

    for (int i1 = 0; i1 < 2; i1++)
    {
        ImageView ne = (ImageView)findViewById(nextimages[i1]);

         ne.setImageResource(photos[generated.get(i1)]);Log.i("test","value:-"+photos[generated.get(i1)]);
    }