Android:用DialogFragment实现LoadingDialog等待加载框

1、先搞好一个等待框的布局:




    

    

 这个布局是这样的:

Android:用DialogFragment实现LoadingDialog等待加载框_第1张图片

 

2、然后开始自定义个DialogFragment了:

/**
 * 等待弹框
 */
public class LoadingDialog extends DialogFragment {

    private String msg = "正在加载";
    private boolean onTouchOutside = true;
    private TextView textView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Objects.requireNonNull(Objects.requireNonNull(getDialog()).getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCanceledOnTouchOutside(onTouchOutside);
        View loadingView = inflater.inflate(R.layout.dialog_loading, container);
        textView= loadingView.findViewById(R.id.textView);
        textView.setText(msg);
        return loadingView;
    }

    public LoadingDialog setMsg(String msg) {
        this.msg = msg;
        if (textView!= null) {
            textView.setText(msg);
        }
        return this;
    }

    public LoadingDialog setOnTouchOutside(boolean onTouchOutside) {
        this.onTouchOutside = onTouchOutside;
        if(getDialog() != null){
            getDialog().setCanceledOnTouchOutside(onTouchOutside);
        }
        return this;
    }
}

 

3、使用:

private LoadingDialog loadingDialog;

//显示等待框
public void showLoading(String msg,boolean touch){
    if(loadingDialog == null){
        loadingDialog = new LoadingDialog();
    }else{
        loadingDialog.dismiss();
    }
    loadingDialog.setMsg(msg)
            .setOnTouchOutside(touch)
            .show(getSupportFragmentManager(),"loading");
            //fragment的话就把getSupportFragmentManager参数换成getChildFragmentManager
}

//动态修改等待框中的文字
public void setLoadingMsg(String msg){
    if(loadingDialog == null){
        return;
    }
    loadingDialog.setMsg(msg);
}

//隐藏等待框
public void hideLoading(){
    if(loadingDialog != null){
        loadingDialog.dismiss();
    }
}

 打完,收工!

 

你可能感兴趣的:(Android,android,dialogFragment,loading,等待框,加载框)