嘿,我想请求帮助,因为我不知道为什么我的代码不起作用。我是android编程的新手,想要求帮助。
public class MotivationalQuotesMenu extends Activity {
int [] images = {R.drawable.mem1, R.drawable.mem2, R.drawable.mem3};
public static int[] RandomizeArray(int[] images){
Random rgen = new Random(); // Random number generator
for (int i=0; i<images.length; i++) {
int randomPosition = rgen.nextInt(images.length);
int temp = images[i];
images[i] = images[randomPosition];
images[randomPosition] = temp;
}
return images;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.motivationalquotesmenu);
Resources res = getResources();
memetitles = res.getStringArray(R.array.omg);
list = (ListView) findViewById(R.id.listView);
loladapter adapter = new loladapter(this, memetitles, images);
list.setAdapter(adapter);
}
然后......
class loladapter extends ArrayAdapter<String> {
Context context;
//class that shows a specific row in listview
private loladapter(Context c, String[] titles, int imgs[]) {
super(c, R.layout.singlerow, R.id.textView, titles);
this.context = c;
images = imgs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.singlerow, parent, false);
ImageView myimageie = (ImageView) row.findViewById(R.id.imageView);
myimageie.setImageResource(images[position]);
return row;
}
}
随机图像不会显示..只是具有相同顺序的相同数组
答案 0 :(得分:1)
public static int[] RandomizeArray(int[] images){
int[] img=images;
ArrayList<Integer> image= new ArrayList<Integer(Arrays.asList(img));
Collections.shuffle(image);
return images;
}
答案 1 :(得分:0)
在randomizeArray
方法中,您接受一个数组并创建一个完全不同的数组实例。然后你(大概)接受这个新实例并将其存储在变量中,同时适配器仍然保存原始数组。
选项1:修改原始数组
public static void randomizeArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
来源:https://stackoverflow.com/a/1520212/2444099
执行randomizeArray
后,请调用此更新相关列表视图:
mAdapter.notifyDataSetChanged();
选项2:更新适配器中的引用
让适配器有一个更新图像的方法:
public void updateImages(int[] newImages) {
images = newImages;
notifyDataSetChanged();
}
获取新的混洗数组后调用此方法。
超出范围
由于int[] images
仅与适配器类相关,因此您可能应该将定义移动到适配器类并使适配器类保持静态以避免潜在的内存泄漏。