1.首先上布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="300dp"
android:background="@drawable/bg_white_circle"
android:layout_height="150dp">
<TextView
android:id="@+id/tv_1"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="文字 1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_marginTop="20dp"
android:id="@+id/tv_2"
android:text="文字 2"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
2.在drawable中新建圆角背景文件 bg_white_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--圆角半径-->
<corners android:radius="12dp"/>
<!--背景颜色,具体颜色自行在color文件设置-->
<solid android:color="#ffffff"/>
</shape>
3.代码
AlertDialog.Builder builder;
AlertDialog dialog;
public void showDialog() {
builder = new AlertDialog.Builder(this);
dialog = builder.create();
DisplayMetrics dm = getResources().getDisplayMetrics();
int screenWidth_px = dm.widthPixels;
int screenHeight_px = dm.heightPixels;
dialog.show();
//点击空白处不关闭dialog
dialog.setCancelable(false);
//需要设置属性,否则dialog的大小不起作用!必须先show再set属性
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width = (int) (screenWidth_px * 0.7 + 0.5f);
params.height = (int) (0.6 * screenHeight_px + 0.5f);
//设置位置的属性
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
dialogWindow.setGravity(Gravity.CENTER);
lp.x = 0; // 新位置X坐标
lp.y = 0; // 新位置Y坐标
lp.width = 300; // 宽度
lp.height = 150; // 高度
lp.alpha = 0.7f; // 透明度
// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
dialogWindow.setAttributes(lp);
dialogWindow.getDecorView().setPadding(0, 0, 0, 0);//去除边框
View view = View.inflate(this,R.layout.dialog_picpick_three,null);
TextView tv = (TextView) view.findViewById(R.id.tv_1);
TextView tv2 = (TextView) view.findViewById(R.id.tv_2);
tv.setText("测试设置文字及颜色");
tv.setTextColor(Color.RED);
tv2.setText("关闭");
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"点击测试",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// 必须使用这个方法,不能使用dialog.setView()的方法
dialogWindow.setContentView(view);
//设置dialog的背景颜色为透明色,就可以显示圆角了!!
dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogWindow.setAttributes(params);
}
|