0
点赞
收藏
分享

微信扫一扫

自定义Dialog(带圆角自定义宽度)

Star英 2021-09-23 阅读 146

目录

前言

实现一个最简单的自定义Dialog

首先先展示一下如何实现一个最简单的自定义Dialog。
Dialog布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:textSize="16sp"
        android:textColor="#fff"
        android:text="提示信息"
        android:gravity="center"
        android:background="@color/colorAccent"
        android:layout_width="match_parent"
        android:layout_height="35dp" />
    <TextView
        android:textSize="14sp"
        android:text="我是提示信息"
        android:layout_marginTop="20dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <View
        android:layout_marginTop="20dp"
        android:background="#eee"
        android:layout_width="match_parent"
        android:layout_height="1dp"/>
    <TextView
        android:gravity="center"
        android:text="我知道了"
        android:layout_width="match_parent"
        android:layout_height="35dp" />
</LinearLayout>

代码将该布局赋给Dialog:

AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setView(R.layout.dialog_test);
AlertDialog alertDialog = builder.create();
alertDialog.show();

效果如下:(设计师需要我们做一个带圆角的Dialog,很显然没有实现,那么接下来我们就来实现带圆角的Dialog)

实现带圆角的Dialog

要实现带圆角的Dialog,首先我想到了将弹窗的背景设为带圆角的不就行了吗?到底行不行呢?我们来试试。
首先给Layout容器(即上方的LinearLayout)设置一个带圆角的背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#fff"/>
    <corners android:radius="10dp"/>
</shape>

然后给标题TextView设置一个带左上角和右上角的圆角背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorAccent"/>
    <corners android:topRightRadius="10dp" android:topLeftRadius="10dp"/>
</shape>

最后给底部的TextView设置一个带右下角和左下角的圆角背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#fff"/>
    <corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"/>
</shape>

万事俱备让我们来看一下效果吧:

很遗憾还是没有实现我们需要的圆角效果,其实这是因为Android自带的AlterDialog自带背景,需要我们手动将其背景给去掉,这里只需要一行代码即可实现(这里需要在Dialog show之后调用)。

//需要在alertDialog show()之后调用
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

让我们再来看一下效果:

这次圆角效果终于实现了,不过...,这宽度也太宽了吧,一点都不好看,那么接下来我们就来控制一下Dialog的宽度吧。

自定义Dialog宽度

这里修改Dialog宽度也只需要一行代码即可(这里我们设置成了屏幕宽度的四分之三):

alertDialog.getWindow().setLayout( mWidth/4*3, LinearLayout.LayoutParams.WRAP_CONTENT);
//设置背景透明
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

看下效果:

项目源码https://github.com/myml666/DialogDemo

举报

相关推荐

0 条评论