首页 > 解决方案 > 如何在代码中而不是在清单中设置应用程序主题

问题描述

我希望我的应用程序在 Android-TV 上应用 Leanback 主题,在 Android 手机上应用 AppCompat 主题。

原来 manifest.xml

<application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/tv"
            android:usesCleartextTraffic="true"
        >

现在 manifest.xml

<application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
        >

我已经尝试了下面列出的几个版本,但它们都不起作用。所有这些都给出了白色背景。

样式.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="tv" parent="@style/Theme.Leanback"/>
    <style name="phone" parent="@style/Theme.AppCompat"/>
</resources>

MainActivity.kt

class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        application.setTheme(R.style.tv)
        super.onCreate(savedInstanceState)
        showLayout()
    }

    private fun showLayout() {
        setContentView(R.layout.layout_tv)
    }
}

MainActivity.kt

class MainActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            showLayout()
        }

        private fun showLayout() {
            application.setTheme(R.style.tv)
            setContentView(R.layout.layout_tv)
    }
}

MainActivity.kt

class MainActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            showLayout()
        }

        private fun showLayout() {
            val theme = super.getTheme()
            theme.applyStyle(R.style.tv, true)

            setContentView(R.layout.layout_tv)
    }
}

标签: androidkotlin

解决方案


以编程方式设置主题时,必须考虑两件事:

  1. 在调用 super.onCreate之前必须设置主题
  2. 必须为每个活动设置主题并使用活动上下文

因此,在您尝试的三个版本中,第一个是最合适的,但您需要使用活动上下文而不是应用程序上下文调用 setTheme。

换句话说,这样称呼它:

setTheme(R.style.tv)
super.onCreate(savedInstanceState)

推荐阅读