【问题标题】:Override activity's background that was set by theme覆盖由主题设置的活动背景
【发布时间】:2015-12-09 00:48:16
【问题描述】:

我目前有一个用于启动画面的活动。以下是我将主题应用于活动的方式:

<application
    ...

    <activity
        android:name=".activities.SplashActivity"
        android:configChanges="orientation|keyboardHidden"
        android:screenOrientation="portrait"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

SplashTheme 定义如下:

<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:background">@drawable/splash_background</item>
</style>

splash_backround.xml 定义如下:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <bitmap
        android:src="@drawable/login_background"
        android:tileMode="disabled" />
</item>
<item>
    <bitmap
        android:src="@drawable/login_siren"
        android:tileMode="disabled"
        android:gravity="bottom|center_horizontal" />
</item>
<item android:top="120dp">
    <bitmap
        android:src="@drawable/splash_welcome"
        android:tileMode="disabled"
        android:gravity="top|center_horizontal" />
</item>

我没有在 SplashActivity 类的 onCreate() 中调用 setContentView(),所以显示的是 SplashTheme 设置的内容。

出现了一种情况,如果在 Application.onCreate() 上加载失败,我想显示一个 AlertDialog。在我使用它来构建、创建和显示 AlertDialog 时,正在显示初始屏幕。但是,当我显示 AlertDialog 时,它会从 Activity 的主题中分配背景。即使我为显式定义不同背景的 AlertDialog(通过 android:alertDialogTheme 或 android:alertDialogStyle)定义了自定义样式,它也会被 Activity 定义的背景所推翻。因此,我将 SplashTheme 更改为以下内容:

<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_background</item>
</style>

这现在释放了对警报对话框背景的控制,因为我没有在我的 Activity 主题中明确设置 android:background。但是,窗口背景不考虑状态栏(即背景也适用于状态栏下方)。结果,当初始屏幕转换到在其布局中使用相同背景的下一个活动时(由于考虑到状态栏),我得到了一点跳跃。所以,这个解决方案仍然不能如我所愿。

如果我确实使用原始 SplashTheme(我在其中定义 android:background),有没有办法覆盖主题为 AlertDialog 定义的 android:background?

【问题讨论】:

    标签: android android-activity android-alertdialog android-theme android-styles


    【解决方案1】:

    活动主题一旦应用就无法更改。

    有没有办法为AlertDialog 覆盖主题定义的android:background

    AlertDialog 有一个构造函数,它接受themeResId 作为输入。来自docs of AlertDialog (Context context, int themeResId)

    创建一个使用显式主题资源的警报对话框。

    创建一个自定义主题,覆盖android:background 属性,然后使用新创建的主题创建AlertDialog

    Dialog dialog = new AlertDialog(context, R.style.my_dialog_theme);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      相关资源
      最近更新 更多