【问题标题】:One Activity with two themes programmatically以编程方式具有两个主题的一项活动
【发布时间】:2019-11-28 04:13:26
【问题描述】:

我在以编程方式切换活动主题时遇到问题。我有一个路由器活动,它根据某些条件决定要路由的活动。并且该路由器活动可以在两次打开:应用程序启动时间与启动屏幕主题并从某处调用 startActivity 以使用 NoDisplay 或透明主题做出路由器决定。我已经在清单中设置了启动主题,它工作正常。但是在调用 startactivity 时我无法在运行时更改为透明主题。它显示黑色背景色而不是透明色。

RouterActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    val transparent = intent.extras?.getBoolean("Need_Transparent")?:false
    if(transparent) setTheme(R.style.Theme_Transparent)
    super.onCreate(savedInstanceState)
    //no setContentView()
}

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</style>

<style name="Theme.Splash" parent="android:Theme">
    <item name="android:windowBackground">@android:color/holo_green_light</item>
</style>

AndroidManifest.xml:

<activity
        android:name=".RouterActivity"
        android:theme="@style/Theme.Splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

那么我怎样才能使 RouterActivity 具有两个主题:Splash(清单中的默认)和透明主题(使用其他活动的 startActivity 打开)。

【问题讨论】:

标签: android android-activity styles themes


【解决方案1】:

我正在用 Java 提供这个解决方案,希望同样的逻辑也适用于 Kotlin,

设置主题的最佳方法是在您的类中覆盖资源主题并放置与OnCreate 方法中相同的逻辑

@Override
public Resources.Theme getTheme() {
    Resources.Theme theme = super.getTheme();
    if(useAlternativeTheme){
        theme.applyStyle(R.style.AlternativeTheme, true);
    }
      // you could also use a switch if you have many themes that could apply
    return theme;
}

【讨论】:

  • 活动以黑色背景显示。我不知道为什么。
  • 哦,那很糟糕。出于测试目的,您可以将透明的颜色更改为纯色吗?检查主题是否设置好?
  • 使用纯色作品。但是当我设置透明色时,它只显示黑色背景色。
  • 而且,当我在清单中应用透明主题时,它可以工作。似乎只有程序化透明主题不起作用。
  • 那是因为透明主题被应用到实体主题上,因此您无法查看该透明主题,您可以尝试的一件事是更改您的逻辑以首先应用透明主题然后需要时改为实心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 2016-06-20
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多