【问题标题】:Changing the whole application theme dynamically动态更改整个应用程序主题
【发布时间】:2013-12-25 13:00:11
【问题描述】:

我找到了许多动态更改活动主题的方法。
但是我使用了来自 aChartengine 的一些图表和图形,它们不能改变它们的主题,因为它们不仅仅是像活动。
所以,我需要找到一种方法来动态更改应用程序主题,这样我的图表主题也会发生变化!

不知道有没有人能解决这个问题。

这是我的代码,适用于每个活动:

public class Utils
{
    private static int sTheme;

    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    public final static int THEME_PINK = 3;

    /**
     * Set the theme of the Activity, and restart it by creating a new Activity
     * of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;

        activity.finish();

        activity.startActivity(new Intent(activity, activity.getClass()));

    }

    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity)
    {
        switch (sTheme)
        {
        default:
        case THEME_DEFAULT:
            break;
        case THEME_WHITE:
            activity.setTheme(R.style.Theme_white);
            break;
        case THEME_BLUE:
            Log.i("THM", "blue intered in utils");
            activity.setTheme(R.style.Theme_blue);
            break;
        case THEME_PINK:
            activity.setTheme(R.style.Theme_pink);

            break;
        }
    }
}

我使用此代码更改我的活动主题:

Utils.changeToTheme(G.tabActivity, Utils.THEME_DEFAULT);

【问题讨论】:

    标签: android-activity themes android-theme android


    【解决方案1】:

    您可以将当前主题存储在SharedPreferences 中并在应用启动时应用它:

    SharedPreferences pref = context.getSharedPreferences("your_pref_name", android.content.Context.MODE_PRIVATE);
    String theme = pref.getString("your_pref_key", "your_default_theme");
    context.setTheme(theme);
    

    然后,当您更改主题时,您应该重新启动应用程序:

    Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
    finish();
    startActivity(intent);
    

    【讨论】:

    • 正如您在我的代码中看到的那样,我重新启动活动以影响主题。但问题是我的所有主题都用Utils.onActivityCreateSetTheme(this);一一设置为活动,并且没有将主题设置为应用程序的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多