如何使用这两种Ontouch和的onClick一个ImageButton的? [英] how to use both Ontouch and Onclick for an ImageButton?

查看:626
本文介绍了如何使用这两种Ontouch和的onClick一个ImageButton的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我想两件事情发生。

in my app, i want two things to happen.

  1. 当我触摸并拖动的ImageButton,它应该随着我的手指移动。

  1. when i touch and drag the imagebutton, it should move along with my finger.

我用OnTouchListener(),这和它工作正常。

i used OnTouchListener() for this and it works fine.

当我点击的ImageButton,它应该关闭的活动。

when i click the imagebutton, it should close the activity.

我用OnClickListener(),这和它也能正常工作。

i used OnClickListener() for this and it also works fine.

所以,这里是我的问题。每当我移动的ImageButton OnTouchListener被tirggered和ImageButton的移动时,OnClickListener也触发时,当我移动释放按钮结束。

So, here is my problem. whenever i move the imagebutton OnTouchListener is tirggered and the imagebutton moves, the OnClickListener is also triggered at the end when i am releasing the button from moving.

如何在不干扰对方在同一按钮上使用ontouch和的onclick监听器?

how to use ontouch and onclick listeners on the same button without interfering on each other?

推荐答案

试试这可能会帮助你。

没有必要设置的onClick()方法onTouch()会处理这两种情况。

No need to set onClick() method onTouch() will handle both the case.

package com.example.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class MainActivity extends Activity {
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gestureDetector = new GestureDetector(this, new SingleTapConfirm());
        ImageButton imageButton = (ImageButton) findViewById(R.id.img);

        imageButton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

                if (gestureDetector.onTouchEvent(arg1)) {
                    // single tap
                    return true;
                } else {
                    // your code for move and drag
                }

                return false;
            }
        });

    }

    private class SingleTapConfirm extends SimpleOnGestureListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            return true;
        }
    }

}

这篇关于如何使用这两种Ontouch和的onClick一个ImageButton的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆