Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在首选项活动中添加带有后退按钮的操作栏_Android_Android Actionbar_Preferenceactivity - Fatal编程技术网

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

Android 在首选项活动中添加带有后退按钮的操作栏,android,android-actionbar,preferenceactivity,Android,Android Actionbar,Preferenceactivity,以下是我的首选活动: 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(s

以下是我的首选活动:

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);
    }

}

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

您应该做几件事:

  • 将以下内容添加到onCreate of PreferenceActivity中:

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId())
         {
             case android.R.id.home:
                 NavUtils.navigateUpFromSameTask(this);
                 return true;
         }
         return super.onOptionsItemSelected(item);
     }
    
  • 覆盖首选项活动中选择的选项项:

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

    <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>
    
    
    
  • 最后将android:launchMode=“singleTop”放入清单中的MainActivity
    标记中:

    <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>
    
    
    

  • 普娅给出的答案不适用于优惠活动。相反,让您的类扩展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"/>
    

    我需要在我的活动中使用不同的操作栏菜单项,因此我使用单顶启动模式创建了我的主活动。这对于设置我的孩子活动的动作栏非常好,但它使我的首选项活动没有动作栏

    最后,关键在于确保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>
    
        <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>
    

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

     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
     <activity android:name=".User_Settings"
                android:theme="@style/Toolbar_settings_style"></activity>
    
    因此,首先,仅为“设置”活动创建一种样式

    这是我的工具栏样式代码

    <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>
    
    放置上述代码后,我的设置活动如下

    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;
                }
            };
        }
    
    }
    
    <?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>
    
    现在让我们来谈谈真正重要的部分。 转到manifest.xml文件,找到您的设置活动并粘贴到下面的代码中。

     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
     <activity android:name=".User_Settings"
                android:theme="@style/Toolbar_settings_style"></activity>
    
    
    
    这是我的AndroidManifest.xml

    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;
                }
            };
        }
    
    }
    
    <?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>
    
    
    

    这是显示“设置活动”工具栏所需的全部内容。

    请尝试检查此问题。此问题非常有用——新程序员可能不知道搜索操作栏,因为他们只需要一个后退按钮。但首选项活动不会扩展AbbCombatActivity!!抱歉,在我的类扩展时找不到getSupportActionBar()PreferenceActivity@Eslam您可以在创建首选项活动时手动添加“setupActionBar”,并像这样使用private fun setupActionBar(){actionBar?.setDisplayHomeAsUpEnabled(true)}假设您在样式中选择了appBar主题。有时
    getActionBar().setDisplayShowHomeEnabled(true);getActionBar().setDisplayHomeAsUpEnabled(true)
    将在背面图像和应用程序标题之间创建一个奇怪的空格。在这种情况下,您只需要清单中的活动
    。如果任何类型的
    NoActionBar
    主题应用于
    MyPrefsActivity
    ,则此方法将不起作用,因此
    getSupportActionBar()
    调用将返回null。