我想将一些ImageView添加到RelativeLayout视图。
我使用的代码如下:
Thread thread = new Thread(new Runnable() {
ArrayList<ImageView> icons = new ArrayList<ImageView>();
@Override
public void run() {
for (int i = 0; i < 20; i++) {
ImageView imageView1 = new ImageView(G.context);
imageView1.setImageResource(R.drawable.music_icon);
imageView1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
imageView1.getLayoutParams().width = (int) convertDpToPixel(20);
imageView1.getLayoutParams().height = (int) convertDpToPixel(20);
icons.add(imageView1);
Log.i("LOG", "Icons Size: " + icons.size());
Log.i("LOG", "I: " + i);
relativeLayout.addView(icons.get(i));
icons.get(i).startAnimation(animationMusic);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
第一次循环运行正常,但第二次出现错误:
relativeLayout.addView(icons.get(i));
问题出在哪里?
答案 0 :(得分:0)
一个主要问题是从后台线程操纵视图(例如添加视图)。您可以通过使用Android的AsyncTask对象获取类似的异步行为,并从onPostExecute方法执行任何UI操作。
如果不了解您正在做的事情,很难找到适合您的解决方案。我主要指出了代码的主要问题。
尝试以在Android环境中可能更好的方式重写代码:
public void addImageViews() {
for(int i = 0; i < 20; i++) {
asyncAdd(i, G.context);
}
}
protected void asyncAdd(final int index, final Context c) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3000 * index);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
relativeLayout.addView(generateImageView(c));
}
}.execute();
}
protected ImageView generateImageView(Context c) {
ImageView imageView1 = new ImageView(c);
imageView1.setImageResource(R.drawable.music_icon);
imageView1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
imageView1.getLayoutParams().width = (int) convertDpToPixel(20);
imageView1.getLayoutParams().height = (int) convertDpToPixel(20);
return imageView1;
}