请帮忙 我有 3 个 ImageView,我可以使用 3 个 Runnables 通过 TranslateAnimation 移动这 3 个 View 。 这是我的代码:
private Runnable run1= new Runnable() {
public void run() {
if(t1)
{
LayoutParams params1=(LayoutParams) l1.getLayoutParams();
params1.x=x1;
params1.y=y1;
l1.setLayoutParams(params1);
x2=r.nextInt(720-80)+80;
y2=r.nextInt(400-80)+80;
TranslateAnimation ta1 = new TranslateAnimation(0, x2-x1, 0, y2-y1 );
ta1.setDuration(800);
ta1.setFillAfter(true);
l1.startAnimation(ta1);
x1=x2;
y1=y2;
handler.postDelayed(run1, 800);
}
}
}; 然后我有这样的 Run2、run3,并通过调用
来运行它们 this.runOnUiThread(run1);
this.runOnUiThread(run2);
this.runOnUiThread(run3);
在OnCreate中
然后我有带有 int c ImageViews 的数组(例如 c=10,然后 c=20...)
for(j=0;j<c;j++)
{
mp[j] = MediaPlayer.create(getApplicationContext(), soundArray[i[j]]);
images[j]=new ImageView(getBaseContext());
lp[j]=new LayoutParams(50,50, x1[j], y1[j]);
images[j].setLayoutParams(lp[j]);
images[j].setBackgroundResource(imgArray[i[j]]);
images[j].setId(j);
images[j].setOnClickListener((OnClickListener)this);
abs.addView(images[j]);
}
我怎样才能用它做这样的事情?
如何动态创建多个Runnable?
此代码不起作用
for(j=0;j<c;j++)
{
run[j]=new Runnable()
{
public void run() {
if(t[j])
{
params[j]=(LayoutParams) images[j].getLayoutParams();
params[j].x=x1[j];
params[j].y=y1[j];
images[j].setLayoutParams(params[j]);
x2[j]=r.nextInt(720-80)+80;
y2[j]=r.nextInt(400-80)+80;
ta[j] = new TranslateAnimation(0, x2[j]-x1[j], 0, y2[j]-y1[j] );
ta[j].setDuration(200);
ta[j].setFillAfter(true);
images[j].startAnimation(ta[j]);
x1[j]=x2[j];
y1[j]=y2[j];
handler.postDelayed(run[j], 200);
}
}
};
for(j=0;j<c;j++)
{
this.runOnUiThread(run[j]);
}
最佳答案
我创建了单独的类。这个类应该实现 Runnable。
public class Single implements Runnable{
public ImageView img=new ImageView(getBaseContext());
public boolean t=true;
public int x2=0;
public int y2=0;
public void run() {
if(t)
{
LayoutParams params=(LayoutParams) img.getLayoutParams();
params.x=x2;
params.y=y2;
img.setLayoutParams(params);
x2=r.nextInt(randX);
y2=r.nextInt(randY);
TranslateAnimation ta = new TranslateAnimation(0, x2-params.x, 0, y2-params.y );
ta.setDuration(1000);
ta.setFillAfter(true);
img.startAnimation(ta);
handler.postDelayed(this, 1000);
}
}
}
然后我可以动态创建此类的对象数组,并为每个对象运行动画。
public Single[] images;
images=new Single[c];
for(j=0;j<c;j++)
{
images[j]=new Single();
images[j].x2=r.nextInt(randX);
images[j].y2=r.nextInt(randY);
images[j].t=true;
}
for(int j1=0;j1<c;j1++)
{
this.runOnUiThread(images[j1]);
}
关于android - 动态创建 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9202033/