在 android 中向对话框 window 添加边框

Adding border to dialog window in android

我正在尝试为 Android 中的对话框 window 添加边框。使用带有以下行的可绘制对象向对话框 window 添加了圆角

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="5dp"
        android:right="5dp"
        android:bottom="5dp"
        android:top="5dp">
    <shape android:shape="rectangle">
        <solid android:color="#ffbf80" />
        <corners android:radius="30dp" />
        <padding
        android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
    </shape>
    </item>
</layer-list>

为了给对话框添加边框,我尝试添加如下的描边元素

<shape android:shape="rectangle">
    <solid
    android:color="#ffbf80" />
    <stroke android:color="#ff3300" android:width="2dp"/>
    <corners
    android:radius="30dp" />
    <padding
    android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp" />
</shape>

但这是在对话框中的每个元素周围创建边框,例如文本视图、图标、按钮。我只想要 window.

的轮廓边框

我使用 AlertDialog.Builder、

在 java 代码中创建了警报对话框
myDialogBuilder=new AlertDialog.Builder(new 
ContextThemeWrapper(getActivity(), 
R.style.CustomDialog))
.setTitle(title.getText().toString())
.setMessage(myText)
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which)
              {
                 getDialog().dismiss();
              }
              });

myDialog=myDialogBuilder.create();

myDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    Window view=((AlertDialog)dialog).getWindow();
                    view.setBackgroundDrawable(new 
                    ColorDrawable(Color.TRANSPARENT));
                ...
                }
 });

我的styles.xml对话框中有以下内容

 <style name="CustomDialog" parent="@style/ThemeOverlay.AppCompat.Dialog">
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:background">@drawable/dialog_bg</item>
    <item name="android:textColorPrimary">@color/my_textcolor</item>
</style>

请帮助我了解我应该进行哪些更改才能显示警告对话框边框。

谢谢

我的应用程序中有圆角对话框,但我使用自定义布局的自定义对话框而不是标准的 AlertDialog,当然它需要更多工作。

  • 在 styles.xml 中用 :
    定义你的 MyDialogStyle <item name="android:background">@drawable/my_rounded_background</item>

  • 在对话框布局的根项中 xml 添加属性 :
    style="@style/MyDialogStyle"

  • 在你的对话框中 class onCreate 添加:

getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

通过对代码进行以下更改,我能够解决警报对话框的边框问题。

我没有在创建对话框时指定主题,而是在 dialog.setOnShowListener()

中将可绘制资源添加到对话框 window
Window view=((AlertDialog)dialog).getWindow();
view.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// to get rounded corners and border for dialog window
view.setBackgroundDrawableResource(R.drawable.dialog_bg);

我的警报对话框中只需要一个标题、消息和一个按钮。所以我使用标准 AlertDialog.Builder 创建它的方式,尽管它也可以使用自定义布局文件和设置视图来完成。