我想在用户触摸对话框片段之外时执行一些任务。我怎么能这样做?
在我的custmom对话框片段中,有一段代码可防止对话在外面触摸时关闭:
getDialog()setCanceledOnTouchOutside(假);
答案 0 :(得分:1)
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make us non-modal, so that others can receive touch events.
getWindow().setFlags(LayoutParams.FLAG_NOT_TOUCH_MODAL, LayoutParams.FLAG_NOT_TOUCH_MODAL);
// ...but notify us that it happened.
getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
// Note that flag changes must happen *before* the content view is set.
setContentView(R.layout.my_dialog_view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// If we've received a touch notification that the user has touched
// outside the app, finish the activity.
if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
//outside touch event
return true;
}
// Delegate everything else to Activity.
return super.onTouchEvent(event);
}
}
参考:Look at the second answer here.
P.S。在问题中,他说他的对话主题活动。
答案 1 :(得分:0)
然后,您需要删除getDialog().setCanceledOnTouchOutside(false);
并使用一些反射来利用Window
的隐藏方法来决定何时关闭对话框:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return object : Dialog(activity as Context, theme) {
override fun onTouchEvent(event: MotionEvent): Boolean {
if (dialogShouldCloseOnTouch(window, context, event)) {
// do custom logic
return true
} else {
return super.onTouchEvent(event)
}
}
}
}
private fun dialogShouldCloseOnTouch(window: Window,
context: Context,
event: MotionEvent): Boolean {
val method = window.javaClass.getMethod("shouldCloseOnTouch", Context::class.java, MotionEvent::class.java)
return method.invoke(window, context, event) as Boolean
}