android - 如何为动画 ImageView 设置 onclick 监听器

标签 android animation imageview

我正在开发一个应用程序,它具有从右向中心移动的动画 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/

相关文章:

java - 跨不同类使用 A 变量。安卓系统

ios - Xcode 8 swift 3 : Modal presentation transitioning delegate not called

android - SimpleCursorAdapter 如何显示图像?

android - 从拍摄的照片中放入 ImageView 的图像并不总是显示

Android WebRTC 崩溃

android - 在 JobService 上调用 StopSelfResult

android - 从android中的Fragment访问工具栏textview

javascript - D3 可选过渡

android - 一段时间后 Android 应用程序滞后

android - 将图像从 sdcard 加载到 imageview 不工作