我有一个带有对话框主题的活动,当有人触摸此活动窗口之外的任何位置的屏幕时,我想关闭(完成)此活动?我怎样才能做到这一点 ?
只是要指出的是is一种从以对话框为主题的活动中获得类似对话框的“触摸外部取消”行为的方法,尽管我还没有完全调查它是否有不需要的副作用。
在 Activity 的 onCreate() 方法中,在创建视图之前,您将在窗口上设置两个标志:一个使其成为“非模态”,以允许除 Activity 视图之外的视图接收事件。第二个是接收其中一个事件已发生的通知,这将向您发送 ACTION_OUTSDIE 移动事件。
如果将活动的主题设置为对话框主题,您将获得所需的行为。
它看起来像这样:
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()) {
finish();
return true;
}
// Delegate everything else to Activity.
return super.onTouchEvent(event);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)