Android自定义Dialog以控制其位置和宽高

1.自定义Dialog类


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

/**
 * Created by yechaoa on 2016/10/22.
 */

public class MyDialog extends Dialog {

    private Window window = null;

    public MyDialog(Context context, boolean cancelable,
                    OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public MyDialog(Context context, int theme) {
        super(context, theme);
    }

    public MyDialog(Context context) {
        super(context);
    }

    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) {
        window = getWindow();//得到对话框的窗口.
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = x;//设置对话框的位置.0为中间
        wl.y = y;
        wl.width = w;
        wl.height = h;
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        wl.gravity = Gravity.CENTER;//设置显示在中间
        window.setAttributes(wl);
    }

}
2.给dialog一个style

     
3.圆角白底xml文件



    
    
    
4.dialog的使用

	final MyDialog dialog=new MyDialog(MainActivity.this, R.style.myDialog);
        final View view = View.inflate(ManifestEditActivity.this, R.layout.dialog_submit,null);
        dialog.setView(view);
        dialog.setProperty(0,0, 600, 400);//设置坐标和宽高
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        Button dialogCancel= (Button) view.findViewById(R.id.dialog_cancel);
        dialogCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Button dialogConfirm= (Button) view.findViewById(R.id.dialog_confirm);
        dialogConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //doSomething
                
            }
        });

你可能感兴趣的:(Android,知识点)