Android:如何在触摸外部时关闭DatePicker DialogFragment? [英] Android: how to dismiss a DatePicker DialogFragment when touching outside?

查看:265
本文介绍了Android:如何在触摸外部时关闭DatePicker DialogFragment?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的DatePickerFragment,它扩展了DialogFragment.我在onCreateDialog()中设置了DatePickerDialog,然后尝试添加:

I have a working DatePickerFragment that extends DialogFragment. I set up a DatePickerDialog in onCreateDialog() and then tried to add:

"picker.setCanceledOnTouchOutside(true);"

"picker.setCanceledOnTouchOutside(true);"

我正在使用Android 8.0 Oreo的设备上进行测试,并且在DatePicker对话框外触摸时什么也没有发生.我正在使用androidx.appcompat.app.AppCompatActivity作为我的BaseActivity和DialogFragment的androidx.fragment.app.DialogFragment;

I am testing on a device with Android 8.0 Oreo and nothing happens when touching outside the DatePicker dialog. I am using androidx.appcompat.app.AppCompatActivity as my BaseActivity and androidx.fragment.app.DialogFragment for the DialogFragment;

代码:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    DatePickerDialog picker = new DatePickerDialog(getActivity(),this,year,month,day);
    **picker.setCanceledOnTouchOutside(true);**
    return picker;

这是创建片段的活动代码:

This is the Activity code that creates the Fragment:

DatePickerFragment newFragment = new DatePickerFragment();
// tried the below also, with no luck
**newFragment.setCancelable(true);**
newFragment.show(getSupportFragmentManager(), "datePicker");

我也尝试了DialogFragment中的以下操作,但也没有运气:

I also tried the below in the DialogFragment, also with no luck:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   ...
   getDialog().setCanceledOnTouchOutside(true);
   ... 
   }

和:

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

我引用了该帖子以获取可能的答案:如何要在按下对话框外部时关闭DialogFragment?.我在这里想念什么?

I referenced this post for possible answers: How to dismiss a DialogFragment when pressing outside the dialog?. What am I missing here?

推荐答案

如果要关闭扩展DialogFragment的对话框,请编写

if you want to dismiss Dialog that extends DialogFragment, write

setCancelable(true);

setCancelable(true);

在onCreateView内.当您触摸外部时,对话框将消失.

inside onCreateView. The dialog will dismiss when you touching outside.

示例代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     setCancelable(true);
     return super.onCreateView(inflater, container, savedInstanceState);
}

这篇关于Android:如何在触摸外部时关闭DatePicker DialogFragment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆