首页 > 解决方案 > 在这种情况下如何使用触摸监听器

问题描述

我需要帮助无论如何,我正在尝试使用ImageView. 我想要的是,ImageView显示一个默认图像,如果按下 ( OnTouch) [它有一个MotionEvent.ACTION_DOWN块] 来运行帧动画。当您释放触摸[有MotionEvent.ACTION_UP块]时,它应该停止动画并返回默认图像。

注意:帧动画是连续重复的,不应包含默认图像作为循环图像之一。(触摸时不应显示按钮向上图像)

现在的问题是,我有动画工作,但根据 android 文档,默认情况下会显示 `` 标签中的第一项。但是如果我将默认图像(按钮未触摸状态)添加为第一项,它将显示在循环中。另外,当我释放触摸时,我使用stop()的方法AnimationDrawable,它在当前帧(图像)处停止动画,我似乎找不到任何方法来停止并进入默认图像状态。

这是我的代码:

button_anim.xml

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item android:drawable="@drawable/button1_press1" android:duration="200" />
<item android:drawable="@drawable/button1_press2" android:duration="200" />
<item android:drawable="@drawable/button1_press3" android:duration="200" />
</animation-list>

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
button = (ImageView)findViewById(R.id.imageView1);

    button.setBackgroundResource(R.drawable.button_anim);
    buttonAnim = (AnimationDrawable)button.getBackground();
    button.setOnTouchListener(buttonTest);
}
private OnTouchListener buttonTest = new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            buttonAnim.start();
            // Log.d("Test", "Touch down");
        } else if (action == MotionEvent.ACTION_UP) {
            buttonAnim.stop();
            // Log.d("Test", "Touch Stop");
        }

        return true;
    }
};

默认图片:- button1_inactive.png

标签: androidandroid-studioanimationdrawableandroid-drawable

解决方案


一个天真的解决方案是在停止后重新分配默认图像,因此:

...
else if (action == MotionEvent.ACTION_UP) {
        buttonAnim.stop();
        button.setBackgroundResource( /** Assign again here the default image */ );
    }
...

用您的默认图像标识符或可绘制替换“在此处再次分配默认图像”注释。

并且从逻辑上讲,在按下时再次将 R.drawable.button_anim 分配给按钮,然后再次开始动画。


推荐阅读