因为有很多时候需要弹出一个Dialog,但系统自带的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>
标签里、<LinearLayout>
外边加上一个控件,设置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>
创建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();
宽度设置为手机屏幕的宽度,高度为控件高度之和,因为没有父layout,所以没有需要自定义View,重写onDraw()
方法,才能使用MarginLayoutParams.MATCH_PARENT
属性
网友评论