1

我的 xml 文件中有一个 ImageView,我想在单击时旋转图像。

我使用以下代码存档:

@Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            img = (ImageView) findViewById(R.id.imageView1);
            Animation an = new RotateAnimation(0.0f, 360.0f, img.getWidth() / 2,
                    img.getHeight() / 2);
            an.reset();
            // Set the animation's parameters
            an.setDuration(1000); // duration in ms
            an.setRepeatCount(0); // -1 = infinite repeated
            an.setRepeatMode(Animation.REVERSE); // reverses each repeat
            an.setFillAfter(true); // keep rotation after animation
            //an.start();
            img.setAnimation(an);


        }
        return true;
    }

但问题是,当我按下图像时,没有任何反应,图像不会转动。但是,如果我单击图像,然后单击 TextView,图像会旋转。

这太随意了。

我究竟做错了什么?我怎样才能解决这个问题?

谢谢。

4

2 回答 2

0

好吧,您似乎正在为整个活动调用 onTouchEvent 函数。因此,任何未被活动窗口内的视图“消耗”的触摸动作都将触发此功能。因此,您触摸活动中的某个位置(例如 TextView)会触发此图像旋转是合乎逻辑的。

看到你的代码我最好的猜测是:最好为你的 ImageView 本身实现一个触摸/点击事件监听器,而不是你的整个 Activity。这是执行此操作的代码片段:

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    /*YOUR CUSTOM CODE AT ACTIVITY CREATION HERE*/

    /*here we implement a click listener for your ImageView*/
    final ImageView img = (ImageView)findViewById(R.id.imageView1);
    img.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Animation an = new RotateAnimation(0.0f, 360.0f, img.getWidth() / 2, img.getHeight() / 2);
            an.reset();
            /* Set the animation's parameters*/
            an.setDuration(1000); // duration in ms
            an.setRepeatCount(0); // -1 = infinite repeated
            an.setRepeatMode(Animation.REVERSE); // reverses each repeat
            an.setFillAfter(true); // keep rotation after animation
            //an.start();
            img.setAnimation(an);
            img.invalidate(); //IMPORTANT: force image refresh

        }
    });
}
于 2012-04-29T01:44:03.017 回答
0

我会支持 epihoms 的推荐(使用 OnClickListener)。另外,请确保您的 ImageView 可以接收点击:

final ImageView img = (ImageView)findViewById(R.id.imageView1);
img.setClickable(true);
img.setFocusable(true);
img.setOnClickListener(new View.OnClickListener(){
    ...

您也可以在 XML 布局中设置这些值:

android:clickable="true"
android:focusable="true"
于 2012-04-29T04:31:49.813 回答