android – How to setTheme to an activity at runtime? It doesn't work call setTheme before onCreate and setContentView-ThrowExceptions

Exception or error:

I want setTheme to an activity at runtime, I have search some solutions by google.
someone said call setTheme before onCreate and setContentView can works, the code section like

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

but it not works, I want to know, is there another solution can setTheme to activity?

How to solve:

Just try this – set your theme after super.onCreate(savedInstanceState); and before setContentView(...)

Like below code –

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

###

Actually this only worked for me if I set it before calling 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...
}

###

setContentView(...);
setTheme(R.style.MyTheme);
setContentView(...);

It must work well..

More on Themes, Read this
http://entertheinfinity.blogspot.in/2016/06/designing-android-interface-themes.html

###

To set the theme at runtime and fix the “black background” problem:

  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>
      

Leave a Reply

Your email address will not be published. Required fields are marked *