Android 小技巧之自定义 Dialog

1. 自定义Dialog类

package com.epro.test.widget;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created on 2019/11/25 15:34
 *
 * @author Gong Youqiang
 */
public class CustomDialog extends Dialog {
    private Window mWindow;

    public CustomDialog(@NonNull Context context) {
        super(context);
    }

    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected CustomDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public void setView(View view) {
        setContentView(view);
    }

    public void setView(int ID) {
        setContentView(ID);
    }

    public void setProperty(int x,int y,int w,int h) {
        mWindow = getWindow();
        WindowManager.LayoutParams params = mWindow.getAttributes();
        params.x = x;  //设置对话框的位置,0为中间
        params.y = y;
        params.width = w;
        params.height = h;
        params.alpha = 1.0f; //设置对话框的透明度,1f不透明
        params.gravity = Gravity.CENTER; //设置显示在中间
        mWindow.setAttributes(params);
    }
}

2. 给 Dialog 设置 Style,style.xml 添加


3. dialog 白色圆角背景。



    
    
    

4. dialog 的使用

import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.epro.test.widget.CustomDialog;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private CustomDialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.button)
    public void onViewClicked() {
        showDialog();
    }

    private void showDialog() {
        mDialog = new CustomDialog(this,R.style.customDialog);
        View view = View.inflate(this, R.layout.dialog_submit,null);
        mDialog.setView(view);
        mDialog.setProperty(0,0,800,600);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.show();
    }

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

你可能感兴趣的:(Android 小技巧之自定义 Dialog)