因為有很多時候需要彈出一個Dialog,但系統(tǒng)自帶的Dialog太丑了,于是寫一個自定義Dialog布局的模板。
layout布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="50dp" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dialog_bg" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
布局稍微改改就能做成點擊右上取消的樣子。在<FrameLayout>標(biāo)簽里、<LinearLayout>外邊加上一個控件,設(shè)置android:layout_gravity="top|right"
FrameLayout的背景
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="2dp"
android:color="#bfe9ff" />
<corners android:radius="10dp" />
<solid android:color="#ffffff" />
</shape>
Dialog的樣式
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="simpleDialogStyle" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
創(chuàng)建Dialog
int mWindowWidth, mWindowHeight;
Dialog dialog = new Dialog(this, R.style.simpleDialogStyle);
View view = LayoutInflater.from(this).inflate(R.layout.simple_dialog, null);
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
mWindowWidth = displayMetrics.widthPixels;
mWindowHeight = displayMetrics.heightPixels;
dialog.setContentView(view, new MarginLayoutParams(mWindowWidth,
MarginLayoutParams.MATCH_PARENT));
dialog.show();
寬度設(shè)置為手機屏幕的寬度,高度為控件高度之和,因為沒有父layout,所以沒有需要自定義View,重寫onDraw()方法,才能使用MarginLayoutParams.MATCH_PARENT屬性