我想要做的是每次点击TextView时,星星都会得到我在布局中设置的随机位置。
首次点击后它会起作用,但下一次点击文字视图时会遗漏一些星星。
List<Integer> imageViews = new ArrayList<Integer>();
List<Integer> images = new ArrayList<Integer>();
public void clearimg()
{
str1.setImageResource(android.R.color.transparent);
str2.setImageResource(android.R.color.transparent);
str3.setImageResource(android.R.color.transparent);
str4.setImageResource(android.R.color.transparent);
str5.setImageResource(android.R.color.transparent);
str6.setImageResource(android.R.color.transparent);
str7.setImageResource(android.R.color.transparent);
str8.setImageResource(android.R.color.transparent);
str9.setImageResource(android.R.color.transparent);
str10.setImageResource(android.R.color.transparent);
}
public void viewadd()
{
imageViews.add(R.id.star1);
imageViews.add(R.id.star2);
imageViews.add(R.id.star3);
imageViews.add(R.id.star4);
imageViews.add(R.id.star5);
imageViews.add(R.id.star6);
imageViews.add(R.id.star7);
imageViews.add(R.id.star8);
imageViews.add(R.id.star9);
imageViews.add(R.id.star10);
}
public void imageadd()
{
images.add(R.drawable.star1);
images.add(R.drawable.star2);
images.add(R.drawable.star3);
images.add(R.drawable.star4);
images.add(R.drawable.star5);
images.add(R.drawable.star6);
images.add(R.drawable.star7);
images.add(R.drawable.star8);
images.add(R.drawable.star9);
images.add(R.drawable.star10);
}
View.OnClickListener tapHandler = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
clearimg();
imageadd();
viewadd();
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
while(true)
{
Integer next = rng.nextInt(imageViews.size()) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews.get(next));
iv.setImageResource(images.get(next));
images.remove(next);
imageViews.remove(next);
break;
}
}
}
}
};
答案 0 :(得分:1)
List<Integer> views = new ArrayList<Integer>();
List<Integer> images = new ArrayList<Integer>();
//populate your lists
您应该从列表中删除已使用的资源。这是一个例子。 在你的时间:
Integer next = rng.nextInt(views.size()) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(views.get(next));
iv.setImageResource(images.get(next));
images.remove(next);
views.remove(next);
break;
}