关闭onTouchOutside上的DialogFragment(不是Dialog)

C.d*_*.d. 19 android dialog touch-event android-fragments android-dialogfragment

我已经搜索了有关解除对话onTouchOutside的所有答案,但是,我在我的应用程序中使用了DialogFragment.当用户在DialogFragment区域外单击时,如何解除DialogFragment.

我已经检查对话框源代码setCanceledOnTouchOutside

public void setCanceledOnTouchOutside(boolean cancel) {
    if (cancel && !mCancelable) {
        mCancelable = true;
    }

    mCanceledOnTouchOutside = cancel;
}
Run Code Online (Sandbox Code Playgroud)

还有另一个可能有趣的功能是isOutOfBounds

private boolean isOutOfBounds(MotionEvent event) {
    final int x = (int) event.getX();
    final int y = (int) event.getY();
    final int slop = ViewConfiguration.get(mContext).getScaledWindowTouchSlop();
    final View decorView = getWindow().getDecorView();
    return (x < -slop) || (y < -slop)
    || (x > (decorView.getWidth()+slop))
    || (y > (decorView.getHeight()+slop));
}
Run Code Online (Sandbox Code Playgroud)

但我无法找到一种方法来使用这些用于DialogFragment

除了这些,我已经用hierarchyviewer检查了应用程序的状态,据 我了解,我只能看到对话框的区域,而不是它的外部部分(我的意思是DialogFragment之后屏幕的剩余部分).

你能建议一种为DialogFragment实现这个setCanceledOnTouchOutside的方法吗?如果可能的话,还有一个示例代码?

Fen*_*res 34

答案很简单:

MyDialogFragment fragment = new MyDialogFragment(); // init in onCreate() or somewhere else
...
if ( fragment.getDialog() != null )
    fragment.getDialog().setCanceledOnTouchOutside(true); // after fragment has already dialog, i. e. in onCreateView()
Run Code Online (Sandbox Code Playgroud)

有关DialogFragments中对话框的详细信息,请参阅http://developer.android.com/reference/android/app/DialogFragment.html#setShowsDialog%28boolean%29.

  • 以上回答并不意味着它有.`DialogFragment`有方法`getDialog()`,它返回`Dialog`,HAS方法`setCanceledOnTouchOutside()`.请仔细阅读答案. (12认同)
  • 哦,男人..请更具描述性..如果你能编辑答案,我可以进行投票.我在自定义`DialogFragment`实现的`onCreateView()`中调用它,它运行良好.谢谢. (3认同)

eri*_*osg 11

在大多数情况下,getDialog()为null,因为在创建对话框的新实例后不会立即获取它.

如上所述onViewCreated,DialogFragment特别是在使用时也是正确的android.support.v4.app.DialogFragment.

以下效果很好,因为它放在onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getDialog() != null) {
        getDialog().setCanceledOnTouchOutside(true);
    }
    return super.onCreateView(inflater, container, savedInstanceState);
}
Run Code Online (Sandbox Code Playgroud)


ast*_*ryk 5

为什么不覆盖onCreateDialog并在此处设置它呢?这样,您不必一直在getDialog()通话中检查是否为空。

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
     Dialog d =  super.onCreateDialog(savedInstanceState);
     d.setCanceledOnTouchOutside(false);
     return d;
 }
Run Code Online (Sandbox Code Playgroud)