如何在运行时为活动设置主题?在onCreate和setContentView之前调用setTheme无法生效。

26

我希望你能帮我翻译一下关于IT技术的内容。需要翻译的内容是如何在运行时为一个活动设置主题,我已经通过谷歌搜索了一些解决方案。有人说在onCreate和setContentView之前调用setTheme可以起作用,代码段如下:

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme_Translucent_NoTitleBar);
    super.onCreate(savedInstanceState);
    ...
    setContentView(...)
}

但它不起作用,我想知道是否有另一种解决方案可以将主题设置为活动?

3
尝试一下这个 - 在 super.onCreate(savedInstanceState); 之后、setContentView(...) 之前设置你的主题。 - Praveenkumar
@hermanbrain:除非你打算修改传递给它的“Bundle”,否则在onCreate(...)方法中始终首先调用super.onCreate(...)。如SpK所说,在调用super.onCreate(...)后调用setTheme(...) - Squonk
同样的问题,我甚至尝试按照Praveen所说的方式放置它,但没有成功。我在style.xml中制作了一个自定义主题,并添加了一行setTheme(R.style.MyCustomTheme); 我需要做其他什么吗? - Srujan Barai
4个回答

23

尝试这样做 - 在super.onCreate(savedInstanceState);之后和setContentView(...)之前设置您的主题。

就像下面的代码一样 -

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Translucent_NoTitleBar); // Set here
    setContentView(...)
}

5
我试过这个,但它显示黑色背景,你能帮我吗? - mdDroid
1
@mdDroid,你找到黑色背景的解决方案了吗? - Adi

10

实际上,只有在调用 super.onCreate(savedInstanceState); 之前设置才能对我起作用。

public void onCreate(Bundle savedInstanceState)
{
    final int themeRes = getIntent().getIntExtra(EXTRA_THEME_ID, 0);
    if (themeRes != 0) setTheme(themeRes);
    super.onCreate(savedInstanceState);
    //ect...
}

4
为了在运行时设置主题并解决“黑色背景”问题:
  1. the theme should be set before onCreate().

    public void onCreate(Bundle savedInstanceState) {
        setTheme(android.R.style.Theme_Translucent_NoTitleBar);
        super.onCreate(savedInstanceState);
        ...
        setContentView(...)
    }
    
  2. the theme of the transparent activity in the android manifest should be set to any theme that has a transparent background (e.g. a dialog theme).

    • this tells the Android OS continue to draw the activities behind the transparent activity so that you don't end up with a black background.

    • i'm using an AppCompatActivity; i need to use an AppCompat theme:

      <?xml version="1.0" encoding="utf-8"?>
      <manifest
          xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">
          ...
          <application
              ...>
              ...
              <activity
                  android:name=".TranslucentActivity"
                  android:theme="@style/Theme.AppCompat.DayNight.Dialog"
                  .../>
              ...
          </application>
      </manifest>
      

谢谢,当您的第三个模块动态设置主题并且“app”模块使用“Material Theme”时,在AndroidManifest中设置主题是有效的。 - rosuh

4

我使用这种技术来更改应用程序的启动活动主题。这是因为在onCreate中没有View(即没有加载操作栏或任何视图的活动)可以设置主题。 在setContentView()之前设置主题就像将主题设置为null View。我的比喻。决定权永远掌握在你手中。 - Umesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接