Android更改原生Dialog的宽高
重点代码
特别注意:需要在dialog show 之后再去设置。
if (mAlertDialog.getWindow() != null) {
WindowManager.LayoutParams lp = mAlertDialog.getWindow().getAttributes();
lp.width = 300; // 宽度,可根据屏幕宽度进行计算
lp.gravity = Gravity.CENTER;
mAlertDialog.getWindow().setAttributes(lp);
}
Activity
package com.demo.testdemo;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Dialog 显示方式一
*/
public void DialogTest1(View view) {
AlertDialog mAlertDialog = new AlertDialog.Builder(this)
.setTitle("标题")
.setMessage("内容").setCancelable(false)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
// 先显示,再更改宽高;否则设置属性不成功
if (mAlertDialog.getWindow() != null) {
WindowManager.LayoutParams lp = mAlertDialog.getWindow().getAttributes();
lp.width = 300; // 宽度,可根据屏幕宽度进行计算
lp.gravity = Gravity.CENTER;
mAlertDialog.getWindow().setAttributes(lp);
}
}
/**
* Dialog 显示方式二
*/
public void DialogTest2(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("标题");
builder.setMessage("内容");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog mAlertDialog = builder.create();
mAlertDialog.show();
// 先显示,再更改宽高;否则设置属性不成功
if (mAlertDialog.getWindow() != null) {
WindowManager.LayoutParams lp = mAlertDialog.getWindow().getAttributes();
lp.width = 500; // 宽度,可根据屏幕宽度进行计算
lp.gravity = Gravity.CENTER;
mAlertDialog.getWindow().setAttributes(lp);
}
}
}
layout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="DialogTest1"
android:text="DialogTest1" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="DialogTest2"
android:text="DialogTest2" />