如何使用View.OnTouchListener代替onClick [英] How to use View.OnTouchListener instead of onClick

查看:249
本文介绍了如何使用View.OnTouchListener代替onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为客户开发一个Android 2.2.2应用程序,他想执行以下操作:

I'm developing an Android 2.2.2 application for a client and he wants to do the following:

现在我有一个带有onClick事件的按钮,但他不喜欢,他想在用户释放按钮时进行检测.

Now I have a button with an onClick event but he doesn't like, he wants to dectect when user release the button.

我找到了 View.OnTouchListener ,我认为这是我需要的使用,但是是否有可能像我使用onClick一样将事件添加到xml中?

I've found View.OnTouchListener which I think this is what I need to use but, is there any posibility to add this event to xml like I did with onClick?

<ImageButton
    android:id="@+id/btnSaveNewGate"
    android:layout_width="@dimen/btnSaveNewGate_width"
    android:layout_height="@dimen/btnSaveNewGate_height"
    android:layout_below="@+id/radioGrGateType"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="@dimen/btnSaveNewGate_marginTop"
    android:background="@null"
    android:contentDescription="@string/layout_empty"
    android:onClick="onSaveNewGateClick"
    android:scaleType="fitXY"
    android:src="@drawable/save_gate_selector" />

我还有两个问题:

用户松开手指时与哪个事件相关?

Which is the event associated when user releases his finger?

是否有禁止使用View.OnTouchListener代替onClick的准则?

Is there any guidelines which prohibit using View.OnTouchListener instead of onClick?

推荐答案

用户松开手指时的事件是MotionEvent.ACTION_UP.我不知道是否有任何准则禁止使用View.OnTouchListener代替onClick(),这很可能取决于情况.

The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.

这是示例代码:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            // Do what you want
            return true;
        }
        return false;
    }
});

这篇关于如何使用View.OnTouchListener代替onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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