我正在开发一个应用程序,它具有从右向中心移动的动画 ImageView 。当单击图像时,将调用 OnClick()。但是,当我在图像移动路径(靠近 ImageView )中单击屏幕时,也会触发 OnClick()。请告诉我如何仅针对 ImageView 设置点击监听器。 我的代码是:
ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.setGravity(Gravity.CENTER);
imageView=new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.moveimage1);
int width=getWindowManager().getDefaultDisplay().getWidth()/2;
System.out.println("width==="+width);
moveLefttoRight = new TranslateAnimation(width, 0, 0, 0);
moveLefttoRight.setDuration(3000);
moveLefttoRight.setRepeatCount(TranslateAnimation.INFINITE); // animation repeat count
moveLefttoRight.setRepeatMode(2);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();
System.out.println("Clicked");
}
});
imageView.startAnimation(moveLefttoRight);
ll.addView(imageView);
setContentView(ll);
最佳答案
一旦动画完成,您就可以附加 onclick 监听器。 对于一个更可靠的解决方案,创建一个工作线程来处理所有需要为动画完成的计算,并且只更新主线程上的实际绘图。例如:
ScheduledExecutorService executor = Executors
.newScheduledThreadPool(1);
// Execute the run() in Worker Thread every REFRESH_RATE
// milliseconds
mMoverFuture = executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
// TODO - implement movement logic.
if (moveWhileOnScreen()) {
stop(false);
}
else {
postInvalidate();
}
}
}, 0, REFRESH_RATE, TimeUnit.MILLISECONDS);
这样你就可以在不干扰移动的情况下附加 onclick 监听器。
关于android - 如何为动画 ImageView 设置 onclick 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216585/