简单好用的自定义DialogFragment

现在有了DialogFragment,所有原来的Dialog就不要使用了。DialogFragment方便又好用,而且屏幕旋转的时候还会保持。下面我简单封装了一个DialogFragment,供自己使用,给大家参考。先贴个图:


没有重写onCreateDialog,因为重写onCreateDialog不能很好的适配圆角(圆角dialog使用还是很多的)。采用的是重写onCreatView,在该方法里return自定的布局。在这里return的view自定义的样式会很好的保留。

然后在onStart中设置屏幕的宽高,这里我获取了屏幕的宽度,设置一个对外的ratio(范围0f~1.0f),可供设置宽度比例,高度默认。

使用方法非常简单,代码如下:

    /**
     * 自定义对话框2
     *
     * @param v 2
     */
    private void showDialog2(View v) {
        final DialogFragment2 df2 = DialogFragment2.newInstance(R.layout.dialog_fragment, 0.75f);
        //设置是否可以取消,包括点击旁边消失
        df2.setCancelable(false);
        //show
        df2.show(getFragmentManager(), getLocalClassName());
        //里面控件点击事件
        View view = df2.getView(mContext);
        if (view != null) {
            view.findViewById(R.id.main_btn_ok).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showToastShort("确定");
                    // TODO: 2016/9/21 dosomething 
                    //这里需要调用一下,才会消失
                    df2.dismiss();
                }
            });
            view.findViewById(R.id.main_btn_cancle).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showToastShort("取消");
                    // TODO: 2016/9/21 dosomething 
                    //这里需要调用一下,才会消失
                    df2.dismiss();
                }
            });
        }
    }


自定义DialogFragment内容如下:

package com.yhq.formwork.view;

import android.app.DialogFragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

/**
 * 邮箱:yhaiqi@sina.com
 * 时间:2016/9/9 9:28
 * 类介绍:DialogFragment重新onCreateView
 */
public class DialogFragment2 extends DialogFragment {
    private View mView;//自定的view
    private int mResId;//自定的view的id
    private float mRatio = 0.75f;//dialog宽度,默认75%屏幕宽度

    public DialogFragment2() {

    }

    public static DialogFragment2 newInstance(View view) {
        DialogFragment2 fragment2 = new DialogFragment2();
        fragment2.mView = view;
        return fragment2;
    }

    public static DialogFragment2 newInstance(View view, float ratio) {
        DialogFragment2 fragment2 = new DialogFragment2();
        fragment2.mView = view;
        fragment2.mRatio = ratio;
        return fragment2;
    }

    public static DialogFragment2 newInstance(@LayoutRes int resId) {
        DialogFragment2 fragment2 = new DialogFragment2();
        fragment2.mResId = resId;
        return fragment2;
    }

    public static DialogFragment2 newInstance(@LayoutRes int resId, float ratio) {
        DialogFragment2 fragment2 = new DialogFragment2();
        fragment2.mResId = resId;
        fragment2.mRatio = ratio;
        return fragment2;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //去标题栏
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        //背景设置为透明
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        //判断是否是输入的资源id
        if (mView == null && mResId > 0) {
            mView = inflater.inflate(mResId, null);
        }
        //log
        Log.i(getClass().getSimpleName(), "onCreateView");
        return mView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mView = view;
        //log
        Log.i(getClass().getSimpleName(), "onViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置弹出对话框的宽度
        int screenWidth = getScreenWidth(getActivity());
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout(
                    (int) (mRatio * screenWidth),//设置宽度为屏幕宽度的比例
                    window.getAttributes().height//高度用默认高度
            );
        }
    }

    /**
     * 获取自定的view
     *
     * @param context 上下文环境,这里不能用getActivity,因为有可能为null
     * @return view
     */
    public View getView(Context context) {
        //判断是否是输入的资源id
        if (mView == null && mResId > 0) {
            LayoutInflater inflater = LayoutInflater.from(context);
            if (inflater != null) {
                mView = inflater.inflate(mResId, null);
            }
        }
        //log
        Log.i(getClass().getSimpleName(), "getView-->" + (mView == null ? "null" : mView.getId()));
        return mView;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context 上下文环境
     * @return 高度
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Kotlin代码示例,演示如何使用DialogFragment来创建自定义对话框并使用onCreateView方法进行布局,并自定义宽高和window、margin: ```kotlin import android.graphics.Point import android.os.Bundle import android.view.* import androidx.fragment.app.DialogFragment class CustomDialogFragment : DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.fragment_dialog_custom, container, false) //在这里可以对布局中的控件进行初始化和设置 return rootView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.Theme_AppCompat_Dialog) } override fun onStart() { super.onStart() dialog?.window?.apply { val size = Point() val display = windowManager.defaultDisplay display.getSize(size) val width = size.x //设置对话框的宽度为屏幕宽度的80% setLayout((width * 0.8).toInt(), WindowManager.LayoutParams.WRAP_CONTENT) setGravity(Gravity.CENTER) //设置对话框的位置为屏幕中央 attributes?.apply { horizontalMargin = 0.1f //设置对话框的左右margin为屏幕宽度的10% verticalMargin = 0.2f //设置对话框的上下margin为屏幕高度的20% } } } } ``` 在这个示例中,我们重写了onStart方法,该方法在对话框显示前调用。我们在这里获取对话框的窗口,并设置其布局参数。我们首先获取屏幕的宽度和高度,然后将对话框的宽度设置为屏幕宽度的80%,高度为包裹内容。我们还使用setGravity方法将对话框放置在屏幕中央。 我们还使用attributes属性来设置对话框的margin。在这个示例中,我们将左右margin设置为屏幕宽度的10%,将上下margin设置为屏幕高度的20%。 请注意,我们没有在此示例中添加任何逻辑或事件处理程序,因为这取决于对话框的用途。此示例仅用于演示如何使用DialogFragment和onCreateView方法创建自定义对话框,并自定义宽高和window、margin。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值