首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

android中使用DialogFragment

2024-12-20 来源:化拓教育网

今天使用了一下DialogFragment,记录一下使用的步骤,方便以后查阅。
我通过DialogFragment中的onCreateDialog方法创建Dialog,生命周期和Fragment调用有些差别。 onCreateDialog()->onActivityCreated()->onDestroyView()

/**
 * @author xuyan QQ:1213236113
 * @name eng100
 * @class name:com.wanhe.eng100.listening.pro.base
 * @class describe
 * @time 2018/1/30 16:33
 * 对DialogFragment进行封装
 */
public abstract class BaseDialogFragment extends MvpDialogFragment {

    protected Activity mContext;
    private Unbinder unbinder;
    
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initActivityCreated(savedInstanceState);
        async();
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
        Dialog dialog = createDialog();

        unbinder = ButterKnife.bind(this, dialog); // Dialog即View

        return dialog;
    }

    protected abstract Dialog createDialog();

    private void async() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                try {
                    doAsyncWork();
                    e.onNext("");
                    e.onComplete();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    e.onError(ex);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(String msg) {
                        initViewData();
                    }
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        initViewData();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    protected abstract void initViewData();

    protected abstract void doAsyncWork();

    protected abstract void initActivityCreated(Bundle savedInstanceState);



    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        mContext = context;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        try {
            if (unbinder != null)
                unbinder.unbind();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroyView();
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
}

/**
 * @author xuyan QQ:1213236113
 * @name eng100
 * @class name:com.wanhe.eng100.listening.pro.sample
 * @class describe
 * @time 2018/1/30 17:21
 * 支付要弹出的Dialog
 */
public class PayDialogFragment extends BaseDialogFragment {

    @BindView(R.id.tv_sample_title)
    TextView tvSampleTitle;
    @BindView(R.id.tvPrice)
    TextView tvPrice;
    @BindView(R.id.image_wx)
    ImageView imageWx;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.rb_wx)
    AppCompatRadioButton rbWx;
    @BindView(R.id.rlwx)
    RelativeLayout rlwx;
    @BindView(R.id.image_zfb)
    ImageView imageZfb;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.rb_zfb)
    AppCompatRadioButton rbZfb;
    @BindView(R.id.rlZfb)
    RelativeLayout rlZfb;
    @BindView(R.id.rg_container)
    NestMutiRadioGroup rgContainer;
    @BindView(R.id.btnPay)
    Button btnPay;
    @BindView(R.id.imageView)
    ImageView imageView;
    private String price;
    private String bookCode;

    @Override
    protected Dialog createDialog() {
        Dialog dialog = new Dialog(mContext,R.style.Dialog_Bottom);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.dialog_pay);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.windowAnimations = R.style.Dialog_Bottom_Animator;
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        window.setAttributes(lp);
        return dialog;
    }

    @OnClick({R.id.rlwx,R.id.rlZfb})
    public void onClickView(View view){
        switch (view.getId()){
            case R.id.rlwx:
                rbWx.setChecked(true);
                break;
            case R.id.rlZfb:
                rbZfb.setChecked(true);
                break;
        }
    }

    @Override
    protected void initViewData() {
    }

    @Override
    protected void doAsyncWork() {
    }
    
    @Override
    protected void initActivityCreated(Bundle savedInstanceState) {
        LogUtils.i("DialogFragment","initActivityCreated");
        Bundle bundle = getArguments();
        if(bundle!=null){
             bookCode = bundle.getString("BookCode");
             price = bundle.getString("Price");
        }
        if(!TextUtils.isEmpty(price)){
            tvPrice.setText(price.concat("元"));
        }
    }
    
    @Override
    protected void bindPresenter() {
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}

创建好Dialog之后发现并不能完全的靠边靠底,仍然有很大的缝隙,只需要为Dialog设置Style( Dialog dialog = new Dialog(mContext,R.style.Dialog_Bottom);)就可以解决了。
在为Dialog设置背景色为透明时,发现不起作用,只需要为Dialog设置 BackgroundDrawable为ColorDrawable。(dialog.getWindow().setBackgroundDrawable(new ColorDrawable())),就可以实现了。

//style
 <style name="Dialog_Bottom" parent="@android:style/Theme.Dialog">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:background">@color/translate</item>
    </style>
//动画
    <style name="Dialog_Bottom_Animator" mce_bogus="1" parent="android:Animation">
        <item name="@android:windowEnterAnimation">@anim/dialog_enter</item>
        <item name="@android:windowExitAnimation">@anim/dialog_exit</item>
    </style>
这里写图片描述
显示全文