如何在PreferenceActivity中添加工具栏?

19

我想在我的安卓应用的PreferenceActivity中添加ToolBar。我写了以下代码。

  public class SettingsActivity extends PreferenceActivity  {
 SendSMS sms;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
    LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent();
    android.support.v7.widget.Toolbar bar = (android.support.v7.widget.Toolbar) LayoutInflater.from(this).inflate(R.layout.action_bar_setting, root, false);
    root.addView(bar, 0);
    bar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

这在我使用安卓Kitkat手机API 19时能够完美运行,但在API level 10即gingerbread上强制关闭。请给我建议。

7个回答

35

您需要一个包含ToolbarListView的布局,其中ListView的id应该为android:id="@android:id/list"

activity_settings.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/content_frame"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

设置活动(SettingsActivity.java)

public class SettingsActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        addPreferencesFromResource(R.xml.preferences);
        ...
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    private void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
    ...
}

请查看我的完整示例:

参考自Android团队:AppCompatPreferenceActivity


Hidro,为什么布局需要一个ListView? - Geison Santos
4
如果您要覆盖布局,那么PreferenceActivity需要一个具有android:id/listListView。这就是原因。 - hidro
1
现在我可以让它工作了。感谢@hidro的解释。 - Geison Santos
1
对我不起作用...它确实显示了工具栏,但是在首选项布局下。 - codelearner
1
在Android 4.4上,我失去了列表中的填充,因此活动看起来不像本地的。 - Artem Mostyaev
显示剩余2条评论

9

尝试:

public class SettingsActivity extends AppCompatPreferenceActivity {
.....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();
    /* getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new GeneralPreferenceFragment())
            .commit();
    */

    //addPreferencesFromResource(R.xml.pref_general);        
}

private void setupActionBar() {
    ViewGroup rootView = (ViewGroup)findViewById(R.id.action_bar_root); //id from appcompat

    if (rootView != null) {
        View view = getLayoutInflater().inflate(R.layout.app_bar_layout, rootView, false);
        rootView.addView(view, 0);

        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

app_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

2
什么是AppCompatPreferenceActivity? - Eslam Sameh Ahmed
2
@Eslam,这是一个扩展了Preference Activity的类。通过选择“新建”->“设置活动”,它将会显示出来。 - Martin Sing
2
@style/AppTheme.AppBarOverlay@style/AppTheme.PopupOverlay 文件中有什么内容? - naXa stands with Ukraine

4
我有点晚了,但是这里有一个小的修复方案,而不是编写大量代码或添加笨重的库。

前往AndroidManifest.xml并在您的首选项活动中添加自定义主题

 <activity
        android:name=".Dashboard.PreferencepActivity"
        android:label="@string/title_activity_preference"
        android:theme="@style/Pref"></activity>

这是添加到上述@style/Pref的自定义主题。
 <style name="Pref" parent="Theme.AppCompat.DayNight.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

希望这能帮到你!

3

您可以轻松地从@android:style/Theme.Material.Light.DarkActionBar添加工具栏。

AndroidManifest.xml中:

<activity
    android:name=".activity.SettingsActivity"
    android:theme="@style/SettingsTheme"
    android:label="Settings"/>

v21/styles.xml 中。
<style name="SettingsTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>

v14/styles.xml 中,用于支持后退 API。
<style name="SettingsTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/ActionBar.V14.Movie.NoTitle</item>


2

非常容易,通过扩充自定义工具条在我的案例中很好地工作。 在您的Java代码中,请按照以下方式操作:

   public class SettingsPrefActivity extends AppCompatPreferenceActivity {
        //  private static final String TAG = SettingsPrefActivity.class.getSimpleName();

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

            //setting up toolbar
            getLayoutInflater().inflate(R.layout.toolbar_setting, (ViewGroup) findViewById(android.R.id.content));
            Toolbar toolbar = findViewById(R.id.toolbar);
            toolbar.setTitle("Settings");
            setSupportActionBars(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            // load settings fragment
            getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
        }

    }

在你的XML代码中,添加一个首选项类别,如下所示:

  <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
//put below line at the top of your xml preference layout screen..
    <PreferenceCategory android:layout="@layout/toolbar_setting"></PreferenceCategory>

在您的布局资源文件夹toolbar_setting中,

   <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="@dimen/appbar_elevation"
    android:minHeight="?attr/actionBarSize"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

1
这种方法不能解决添加工具栏的问题,但是您可以为设置页面恢复默认的ActionBar。通过继承父主题为设置活动创建主题。
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar.Bridge">
    <!-- Customize your theme here. -->
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.Settings" parent="AppTheme">
    <item name="windowNoTitle">false</item>
    <item name="windowActionBar">true</item>
</style>

在 AndroidManifest.xml 中设置 android:theme
<activity
    android:name=".Settings"
    android:theme="@style/AppTheme.Settings" />

这就是全部。


0

改为:

public class PreferencesActivity extends Activity

做这个:
public class PreferencesActivity extends AppCompatActivity

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