android - 如何在代码中而不是在清单中设置应用程序主题
问题描述
我希望我的应用程序在 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)
}
}
解决方案
以编程方式设置主题时,必须考虑两件事:
- 在调用 super.onCreate之前必须设置主题
- 必须为每个活动设置主题并使用活动上下文
因此,在您尝试的三个版本中,第一个是最合适的,但您需要使用活动上下文而不是应用程序上下文调用 setTheme。
换句话说,这样称呼它:
setTheme(R.style.tv)
super.onCreate(savedInstanceState)
推荐阅读
- javascript - 带有滚动但阻止编辑的HTML文本区域?
- mongodb - 在 mongo 中查找树层次结构
- c# - 在 C# 中为 200 000+ 行寻找快速数据库到对象映射器
- swiftui - 每次渲染正文时都会调用 SwiftUI Picker onReceive()
- python - 是否可以区分 Python 中具有相同变量的两个对象?
- json - jq 过滤内部数组元素但返回整个 JSON
- javascript - 无法读取未定义的属性“列”
- python - 如何在 Django 中添加显示下拉字段
- python - Databricks 连接 & PyCharm & 远程 SSH 连接
- javascript - 如何根据不断变化的道具渲染 v-for?