android,自定义dialog

含义

extends android.app.Dialog,即自定义dialog

设置dialog的视图

一般在构造方法中调用父类的

public void setContentView(@NonNull View view)

获取这个参数view的方法,有如下几种:

①
view = LayoutInflater.from(context).inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

②
binding = DataBindingUtil.inflate(@NonNull LayoutInflater inflater, int layoutId, @Nullable ViewGroup parent,
    boolean attachToParent)
view = binding.getRoot()

设置dialog的宽度

默认dialog的width是固定的MATCH_PARENT,而且载入的layout最外层布局的width无论怎么设置,layout的width都紧贴着dialog

有的时候我们需要改动dialog的宽度,如下:

{ //这是一个构造代码块
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.width = 800;// 单位是px
    getWindow().setAttributes(lp);
}

以上仅仅是设置了dialog一个固定的width,想让width为wrap_content,要在layout外多套一层透明的

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

里面的view就可以正常使用layout_width="wrap_content"

点击空白处不可取消

setCancelable(false)

默认可取消

显示和消失

show()

cancel()
源码:
    /**
     * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will
     * also call your {@link DialogInterface.OnCancelListener} (if registered).
     */
    @Override
    public void cancel() {
        if (!mCanceled && mCancelMessage != null) {
            mCanceled = true;
            // Obtain a new message so this dialog can be re-used
            Message.obtain(mCancelMessage).sendToTarget();
        }
        dismiss();
    }

设置dialog的控件事件

例:

public void setClickListener(OnClickListener listener) {
    if (listener != null) {
        btnConfirm.setOnClickListener(v -> listener.confirmClick());
        btnCancel.setOnClickListener(v -> listener.cancelClick());
    }
}

// 暴露一个内部接口
public interface OnClickListener {
    void confirmClick();

    void cancelClick();
}

猜你喜欢

转载自blog.csdn.net/qq_38861828/article/details/108512351