如何更改PreferenceActivity主题?

Eli*_*vah 13 java android

我正在尝试在我的应用中更改PreferenceActivity的主题,但我无法让它工作.

这是xml:

    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

        <SwitchPreference android:title="Auto Clear" android:key="autoclear" android:summary="Clear the command line when the code is being executed." android:defaultValue="false"/>
        <ListPreference android:title="Choose a theme" android:negativeButtonText="" android:dialogTitle="" android:key="theme" android:entries="@array/themesList" android:entryValues="@array/themesList" android:defaultValue="Default" />

</PreferenceScreen>
Run Code Online (Sandbox Code Playgroud)

这就是PreferenceActivity:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    this.setTheme(R.style.AppTheme);

    addPreferencesFromResource(R.xml.preferences);

}
Run Code Online (Sandbox Code Playgroud)

结果是:

结果

shr*_*046 18

您是否尝试在清单中的活动标签上应用主题?这是我以前做过的 -

<activity 
  android:label="@string/app_name" 
  android:name="com.example.MyPreferenceActivity"
  android:theme="@android:style/Theme.Black"
  android:exported="true"
  android:icon="@drawable/ic_launcher"></activity>
Run Code Online (Sandbox Code Playgroud)

编辑:

您可以尝试的另一个选项是覆盖onApplyThemeResource(Resources.Theme theme, int resid, boolean first).查看android源代码,setTheme将在内部调用方法.

/**
 * Called by {@link #setTheme} and {@link #getTheme} to apply a theme
 * resource to the current Theme object.  Can override to change the
 * default (simple) behavior.  This method will not be called in multiple
 * threads simultaneously.
 *
 * @param theme The Theme object being modified.
 * @param resid The theme style resource being applied to <var>theme</var>.
 * @param first Set to true if this is the first time a style is being
 *              applied to <var>theme</var>.
 */
protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
    theme.applyStyle(resid, true);
}
Run Code Online (Sandbox Code Playgroud)


E P*_*lus 10

最后我发现了如何以编程方式更改主题"PreferenceActivity"(通过java代码)

要更改主题,请执行以下操作:

        @Override
        public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Holo_Theme_Light);
        super.onCreate(savedInstanceState);
        }
Run Code Online (Sandbox Code Playgroud)

始终在setTheme(R.style.yourtheme);方法之前调用super.onCreate(savedInstanceState);方法.通过这样做,它将产生如下所示的结果.

在此输入图像描述

就这样.

如果setTheme(R.style.yourtheme);在方法之后调用方法super.onCreate(savedInstanceState);,它将产生如下所示的结果.

在此输入图像描述

注意:嵌套的PreferenceScreen无法识别主题.要将主题应用于嵌套的PreferenceScreen,您必须为该嵌套的PreferenceScreen和调用setTheme(R.style.yourtheme);方法创建另一个PreferenceActivity .