Custom Alert Dialog looking weird on Android 4.x

孤者浪人 提交于 2019-12-10 03:31:20

问题


I want to customize the alert dialog in my Android app, so I started by changing the alertDialogTheme attribute of my app's theme as follows:

res/values/themes.xml

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:alertDialogTheme">@style/AlertDialogTheme</item>
    </style>

    <style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert"/>
</resources>

Just by doing that, I didn't expected the dialog to look differently from the standard, because the new theme AlertDialogTheme is exactly the same as its parent. It worked properly on Android Lollipop, but in Android Kitkat a white rectangle appears behind the dialog. Here's how it looked like:

Am I doing anything wrong? Maybe using the wrong parent?

Thanks!


回答1:


This happens because you´re using AlertDialog instead of the relatively new AlertDialogCompat. This one brings the same Material Design style dialogs across all platforms and is highly encouraged its use.

To use it, you must be sure that in your Gradle file you have the following line inside your dependencies:

com.android.support:appcompat-v7:24.2.1
(This one is the latest version. Make sure you have all your packages updated by looking into the SDK Manager).

Then in the Activity where you want to show it you must import android.support.v7.app.AlertDialog and use the AlertDialog.Builder exactly as you were using it before.




回答2:


I fixed it by using below code:

 <style name="CustomAppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@android:color/transparent</item>
</style>



回答3:


  1. Add appcompat dependency to your build script:

    implementation 'com.android.support:appcompat-v7:27.1.1'

  2. Replace all usages of android.app.AlertDialog with android.support.v7.app.AlertDialog.




回答4:


For those of you using AndroidX you'll want to use the following import:

import androidx.appcompat.app.AlertDialog


来源:https://stackoverflow.com/questions/33112001/custom-alert-dialog-looking-weird-on-android-4-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!