如何使用 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;
}
});