如何在Android中运行时更改当前主题

Gui*_*ido 144 android themes

我创建了一个PreferenceActivity,允许用户选择他想要应用于整个应用程序的主题.

当用户选择主题时,执行以下代码:

if (...) {
    getApplication().setTheme(R.style.BlackTheme);
} else {
    getApplication().setTheme(R.style.LightTheme);
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我已经使用调试器检查了代码是否正在执行,我也看不到用户界面的任何变化.

主题是定义的res/values/styles.xml,Eclipse没有显示任何错误.

<resources>
    <style name="LightTheme" parent="@android:style/Theme.Light">
    </style>

    <style name="BlackTheme" parent="@android:style/Theme.Black">
    </style>    
</resources>
Run Code Online (Sandbox Code Playgroud)

关于可能发生的事情以及如何解决问题的任何想法?我应该拨打setTheme代码中的任何特殊点吗?如果有帮助,我的应用程序包含几个活动.

Pen*_*m10 84

我也希望看到这个方法,你可以为你的所有活动设置一次.但据我所知,你必须在显示任何观点之前设置每个活动.

供参考检查:

http://www.anddev.org/applying_a_theme_to_your_application-t817.html

编辑(从该论坛复制):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Call setTheme before creation of any(!) View.
     setTheme(android.R.style.Theme_Dark);

    // ...
    setContentView(R.layout.main);
}
Run Code Online (Sandbox Code Playgroud)

  • 请提供一个独立的答案,以便如果该链接死亡,人们仍然可以访问您的答案 (16认同)
  • 它有效,但是在您不从一个Activity更改为另一个Activity之前不会应用更改... (3认同)

TPR*_*eal 58

如果你想改变一个已经存在的活动主题,称recreate()setTheme().

注意:如果更改主题,请不要调用recreate onCreate(),以避免无限循环.

  • 特别是,如果你在`onCreate()`中调用`setTheme()`,在调用super.onCreate()或setContentView()之前,(1)你必须检查以防止无限循环你不断重建; (2)你有什么收获? (3认同)
  • 如果引用一些证据或推理来解释为什么有必要调用`recreate()`,即使文档(http://developer.android.com/reference/android/content/Context),这个答案会更有用. .html #setTheme(int))在实例化任何视图之前只对`setTheme()`说.你是说只有在已经实例化视图的情况下调用recreate()? (2认同)

Yur*_*kov 21

recreate()(如TPReal所述)将仅重新启动当前活动,但之前的活动仍将在后台堆栈中,并且主题将不会应用于它们.

因此,此问题的另一个解决方案是完全重新创建任务堆栈,如下所示:

    TaskStackBuilder.create(getActivity())
            .addNextIntent(new Intent(getActivity(), MainActivity.class))
            .addNextIntent(getActivity().getIntent())
            .startActivities();
Run Code Online (Sandbox Code Playgroud)

编辑:

在UI或其他地方执行主题更改后,只需输入上面的代码即可.您的所有活动都应该具有setTheme()之前调用的方法onCreate(),可能在某些父活动中.这也是存储所选主题SharedPreferences,读取然后使用setTheme()方法设置的常规方法.


Unk*_*own 16

我遇到了同样的问题,但我找到了解决方案.

public class EditTextSmartPhoneActivity extends Activity implements DialogInterface.OnClickListener
{
    public final static int CREATE_DIALOG  = -1;
    public final static int THEME_HOLO_LIGHT  = 0;
    public final static int THEME_BLACK  = 1;

    int position;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        position = getIntent().getIntExtra("position", -1);

        switch(position)
        {
        case CREATE_DIALOG:
            createDialog();
            break;
        case THEME_HOLO_LIGHT:
            setTheme(android.R.style.Theme_Holo_Light);
            break;
        case THEME_BLACK:
            setTheme(android.R.style.Theme_Black);
            break;
        default:
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    }

    private void createDialog()
    {
        /** Options for user to select*/
        String choose[] = {"Theme_Holo_Light","Theme_Black"};

        AlertDialog.Builder b = new AlertDialog.Builder(this);

        /** Setting a title for the window */
        b.setTitle("Choose your Application Theme");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(choose, 0, null);

        /** Setting a positive button and its listener */
        b.setPositiveButton("OK",this);

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** show dialog*/
        d.show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        AlertDialog alert = (AlertDialog)dialog;
        int position = alert.getListView().getCheckedItemPosition();

        finish();
        Intent intent = new Intent(this, EditTextSmartPhoneActivity.class);
        intent.putExtra("position", position);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这适用于您希望用户在运行时选择主题的时间.无需在清单中进行设置 (3认同)
  • 在setTheme()之后调用`super.onCreate()`对于使这个工作也很关键?我的印象是在调用`setContentView()`之前必须调用`setTheme()` (2认同)

Fra*_*ani 10

我有类似的问题,我这样解决了..

@Override
public void onCreate(Bundle savedInstanceState) {

    if (getIntent().hasExtra("bundle") && savedInstanceState==null){
        savedInstanceState = getIntent().getExtras().getBundle("bundle");
    }

    //add code for theme

    switch(theme)
    {
    case LIGHT:
        setTheme(R.style.LightTheme);
        break;
    case BLACK:
        setTheme(R.style.BlackTheme);
        break;

    default:
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //code

}
Run Code Online (Sandbox Code Playgroud)

此代码用于重新创建活动保存包并更改主题.你必须编写自己的onSaveInstanceState(Bundle outState); 从API-11开始,您可以使用recreate()方法

Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();
Run Code Online (Sandbox Code Playgroud)


Lal*_*rma 9

我们必须在调用'super.onCreate()''setContentView()'方法之前设置主题.

查看此链接,以便在运行时将新主题应用于整个应用程序.

  • 显然这意味着“在调用 *super.onCreate()* 和 setContentView() 之前”。顺便说一句,我早些时候否决了这个答案,因为它似乎是错误的;现在我明白了它的意思,并且我看到了它的价值(尽管没有明确表达)。不过,除非答案被编辑,否则我无法更改我的投票。如果发生这种情况,请通知我,以便我更改投票。 (2认同)
  • 我编辑了它并删除了downvote. (2认同)

Vit*_*nko 5

代替

getApplication().setTheme(R.style.BlackTheme);
Run Code Online (Sandbox Code Playgroud)

setTheme(R.style.BlackTheme);
Run Code Online (Sandbox Code Playgroud)

我的代码:在 onCreate() 方法中:

super.onCreate(savedInstanceState);

if(someExpression) {
    setTheme(R.style.OneTheme);
} else {
    setTheme(R.style.AnotherTheme);
}

setContentView(R.layout.activity_some_layout);
Run Code Online (Sandbox Code Playgroud)

某处(例如,单击按钮时):

YourActivity.this.recreate();
Run Code Online (Sandbox Code Playgroud)

您必须重新创建活动,否则 - 不会发生更改