繁体   English   中英

在首选项活动中添加带有后退按钮的操作栏

[英]add action bar with back button in preference activity

这是我的首选活动:

package com.example.hms.test;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PrefsActivity extends PreferenceActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
    }

}

在这里我想显示一个带有名称设置的操作栏和一个返回主页的按钮

你应该做几件事:

  1. 将以下内容添加到 PreferenceActivity 的 onCreate 中:

     getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  2. 覆盖 PreferenceActivity 中的 onOptionsItemSelected:

     @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); }
  3. 将您的 PreferenceActivity 清单中的<activity>标记更改为如下所示:

     <activity android:name=".PrefsActivity" android:label="@string/title_activity_settings" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.android.MainActivity" /> </activity>
  4. 最后将 android:launchMode="singleTop" 放在清单中的 MainActivity <activity>标签中:

     <activity android:name=".MainActivity" android:label="@string/app_name" android:launchMode="singleTop" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

Pooya 给出的答案不适用于 PreferenceActivity。 而是让您的类扩展 AppCompatActivity,并使用 PreferenceFragment 加载首选项。 这是我的设置代码:

public class MyPrefsActivity extends AppCompatActivity {

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

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onSupportNavigateUp(){
        finish();
        return true;
    }

    public static class MyPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}

将活动放在您的 AndroidManifest.XML 中:

<activity android:name=".MyPrefsActivity"
    android:label="Preferences"
    android:theme="@style/AppTheme"/>

现在您可以像往常一样使用我的主活动(或您拥有的任何父活动)中的意图启动设置活动:

Intent prefsIntent = new Intent(activity, MyPrefsActivity.class);
activity.startActivity(prefsIntent);

我的活动中需要不同的操作栏菜单项,因此我使用 singleTop launchMode 创建了 MainActivity。 这对于设置我的孩子活动的操作栏非常有用,但它使我的偏好活动没有操作栏。

最后,关键在于确保 MainActivity 主题具有 Theme.AppCompat.Light.NoActionBar 的父级:

       <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

和 SettingsActivity 主题有父 Theme.AppCompat.Light.DarkActionBar:

    <activity
        android:name=".SettingsActivity"
        android:label="@string/title_activity_settings"
        android:theme="@style/SettingsTheme"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="net.deatrich.app.bodyandminddbt.MainActivity" />
    </activity>

在styles.xml中

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>

</style>

<style name="SettingsTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

可能有更好的方式来设计它,但这是有效的。

对于其他阅读的人,还请记住从 AppCompatPreferenceActivity 派生您的 SettingsActivity:

设置Activity.java:

public class SettingsActivity extends AppCompatPreferenceActivity {

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

    // I'm displaying a fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new GeneralPreferenceFragment())
            .commit();

    setupActionBar();

}


private void setupActionBar() {

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        if (!super.onMenuItemSelected(featureId, item)) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return true;
    }
    return super.onMenuItemSelected(featureId, item);
}
...

好的。 现在您仍然遇到麻烦,那么我为您提供了独特的解决方案,只需稍作改动即可 100% 工作。

所以首先为设置活动创建一种样式。

这是我的工具栏样式代码。

<style name="Toolbar_settings_style" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:colorControlNormal">@color/appTitleTextColor</item>
    </style>

这是我的 stlyes.xml 看起来像

<resources>    
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:colorControlNormal">@color/appTitleTextColor</item>
    </style>

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

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="Toolbar_settings_style" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:colorControlNormal">@color/appTitleTextColor</item>
    </style>   

</resources>

是的。 你注意到我只为 settingsActivity 创建了重复的样式(appTheme 和 Toolbar_settings_style 都是相同的样式属性)。 创建重复样式非常重要。

现在转到您的 settingsActivity 并将以下代码粘贴到 onCreate() 中。

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

现在放置上面的代码后,我的 SettingsActivity 看起来像

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;


import settingspreferences.AppCompatPreferenceActivity;

public class User_Settings extends AppCompatPreferenceActivity {

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

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

    public static class MainPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);

            // gallery EditText change listener
            bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));

            // notification preference change listener

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
             //   onBackPressed();
            }
            return super.onOptionsItemSelected(item);
        }

        private static void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

            sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                    PreferenceManager
                            .getDefaultSharedPreferences(preference.getContext())
                            .getString(preference.getKey(), ""));
        }

        /**
         * A preference value change listener that updates the preference's summary
         * to reflect its new value.
         */
        private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                String stringValue = newValue.toString();

                if (preference instanceof ListPreference) {
                    // For list preferences, look up the correct display value in
                    // the preference's 'entries' list.
                    ListPreference listPreference = (ListPreference) preference;
                    int index = listPreference.findIndexOfValue(stringValue);

                    // Set the summary to reflect the new value.
                    preference.setSummary(
                            index >= 0
                                    ? listPreference.getEntries()[index]
                                    : null);

                } else if (preference instanceof RingtonePreference) {
                    // For ringtone preferences, look up the correct display value
                    // using RingtoneManager.
                    if (TextUtils.isEmpty(stringValue)) {
                        // Empty values correspond to 'silent' (no ringtone).
                        preference.setSummary(R.string.pref_ringtone_silent);

                    } else {
                        Ringtone ringtone = RingtoneManager.getRingtone(
                                preference.getContext(), Uri.parse(stringValue));

                        if (ringtone == null) {
                            // Clear the summary if there was a lookup error.
                          //  preference.setSummary(R.string.summary_choose_ringtone);
                        } else {
                            // Set the summary to reflect the new ringtone display
                            // name.
                            String name = ringtone.getTitle(preference.getContext());
                            preference.setSummary(name);
                        }
                    }

                } else if (preference instanceof EditTextPreference) {
                    if (preference.getKey().equals("key_gallery_name")) {
                        // update the changed gallery name to summary filed
                        preference.setSummary(stringValue);
                    }
                } else {
                    preference.setSummary(stringValue);
                }
                return true;
            }
        };
    }

}

现在让我们进入真正重要的部分。 转到manifest.xml 文件并找到您的 settingsActivity 并粘贴下面的代码。

 <activity android:name=".User_Settings"
            android:theme="@style/Toolbar_settings_style"></activity>

所以这是我的AndroidManifest.xml看起来像

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

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--  -->
        <activity
            android:name=".MainActivity"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- <intent-filter> -->
            <!-- <action android:name="android.intent.action.SEARCH" /> -->
            <!-- </intent-filter> -->

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
        <activity android:name=".Add_Items" />
        <activity android:name=".Product_details_view" />
        <activity
            android:name=".editProducts"
            android:parentActivityName=".Product_details_view" />
        <activity android:name=".User_Settings"
            android:theme="@style/Toolbar_settings_style"></activity>
    </application>

</manifest>

这就是在 settingsActivity 上显示 Toolbar 所需的全部内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM