Dialog自定義布局

因為有很多時候需要彈出一個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屬性

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容