我正在android中实现对话框,如果用户在对话框外单击但我想要在显示对话框时点击对话外部的事件,我希望我的对话框不被解除。
答案 0 :(得分:0)
覆盖对话框的onTouchEvent()并检查操作类型。如果操作类型为MotionEvent.ACTION_OUTSIDE
,则表示用户正在对话框区域外进行交互。因此,在这种情况下,您可以关闭对话框或决定要执行的操作:
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
System.out.println("Touched outside the dialog");
}
return false;
}
答案 1 :(得分:0)
如果要检查触摸是否发生在对话框或视图之外,则必须覆盖活动中的DispatchTouchEvent()
并检入该方法。喜欢 :
创建一个触发touchOutSide的界面,如下所示:
/**
* Interface definition for a callback to be invoked when a touch event has occurred outside a formerly specified view.
* See {@link #setOnTouchOutsideViewListener(View, OnTouchOutsideViewListener)}
*/
public interface OnTouchOutsideViewListener {
/**
* Called when a touch event has occurred outside a given view.
*
* @param view The view that has not been touched.
* @param event The MotionEvent object containing full information about the event.
*/
void onTouchOutside(View view, MotionEvent event);
}
假设您有基本活动,您可以将所有代码放入其中,或者在活动中使用它。
覆盖dispatchTouchEvent()
将在屏幕上触发所有触摸。在这里,我们将在屏幕上显示触摸的 x和y ,因此您必须获取视图 x和y 并检查此点是否在触摸范围内。
@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// Notify touch outside listener if user tapped outside a given view
if (mOnTouchOutsideViewListener != null && mTouchOutsideView != null
&& mTouchOutsideView.getVisibility() == View.VISIBLE) {
Rect viewRect = new Rect();
mTouchOutsideView.getGlobalVisibleRect(viewRect);
if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
mOnTouchOutsideViewListener.onTouchOutside(mTouchOutsideView, ev);
return false;
}
}
}
return super.dispatchTouchEvent(ev);
}
要在侦听器外部设置触摸并将其删除,请在以下活动中创建方法:
/**
* Sets a listener that is being notified when the user has tapped outside a given view. To remove the listener,
* call {@link #removeOnTouchOutsideViewListener()}.
* <p/>
* This is useful in scenarios where a view is in edit mode and when the user taps outside the edit mode shall be
* stopped.
*
* @param view
* @param onTouchOutsideViewListener
*/
public void setOnTouchOutsideViewListener(View view, OnTouchOutsideViewListener onTouchOutsideViewListener) {
mTouchOutsideView = view;
mOnTouchOutsideViewListener = onTouchOutsideViewListener;
}
public void removeOnTouchOutsideViewListener() {
mTouchOutsideView = null;
mOnTouchOutsideViewListener = null;
}
所以最后你应该做的是,将最顶层的父视图传递给setOnTouchOutsideViewListener()
活动中的onCreate()
。在dialog.show()
之后的情况下,传递对话框父布局。喜欢:
View detectTouchOutsideThisView = findViewById(R.id.parent_view);
setOnTouchOutsideViewListener(detectTouchOutsideThisView, new OnTouchOutsideViewListener() {
void onTouchOutside(View view, MotionEvent event) {
//If touch outside this will be triggered
}
});