【问题标题】:Android SharedPreferences not changingAndroid SharedPreferences 没有改变
【发布时间】:2014-03-09 21:39:12
【问题描述】:

所以我正在了解 Android 中的SharedPreferences

我想我会很快尝试模拟一些简单的东西。当用户从选项列表中选择一个特定选项(在这种情况下为 3 个选项) - 布局文件将相应更改。 However, it always assumes the default value supplied, hence never changes the layout when another option is selected - so when another option is selected, it is recorded fine, but the layout doesn't change, this leads me to believe that there is perhaps首先获取偏好时出现问题,我想知道是否有人可以快速查看并发现明显的东西,或者他们的经验/智慧不那么明显 - 这是代码:

MainActivity.java:

package com.example.preferenceslayout;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity
    implements OnSharedPreferenceChangeListener {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case R.id.preferences:
            startActivity(new Intent(getApplicationContext(),
                     AppPreferences.class));
            break;
        }
        return false;
    }

    public void loadPreferences() {
        SharedPreferences prefs = getApplicationContext().
            getSharedPreferences("mode", MODE_PRIVATE);
        int layoutPref = prefs.getInt("mode", 10);
        switch(layoutPref) {
        case 10:
            setContentView(R.layout.activity_main);
            break;
        case 20:
            setContentView(R.layout.second_layout);
            break;
        case 30:
            setContentView(R.layout.third_layout);
            break;
        }
        prefs.registerOnSharedPreferenceChangeListener(MainActivity.this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
        loadPreferences();      
    }
}

preference.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <ListPreference
        android:key="mode"
        android:title="@string/mode"
        android:defaultValue="1"
        android:summary="@string/summary"
        android:entries="@array/listArray"
        android:entryValues="@array/listValues" />
</PreferenceScreen>

AppPreferences.xml:

package com.example.preferenceslayout;

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

public class AppPreferences extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
    }
}

main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>
    <item
        android:id="@+id/preferences"
        android:title="Preferences" />
</menu>

PreferencesLayoutManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.preferenceslayout.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.preferenceslayout.AppPreferences">
            <intent-filter>
                <action android:name=".AppPreferences" />
            </intent-filter>
        </activity>
    </application>
</manifest>

数组.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="listArray">
        <item>10</item>
        <item>20</item>
        <item>30</item>
    </string-array>
    <string-array name="listValues">
        <item>1</item>
        <item>2</item>
    </string-array>
</resources>

【问题讨论】:

  • 我注意到您的首选项文件的名称没有常量或 R 字符串。我喜欢使用 app_name,这样我就可以轻松地将首选项类用于任何应用程序。 SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE);
  • 更好地使用默认共享首选项

标签: android sharedpreferences preferenceactivity


【解决方案1】:

你从不你的喜好。你需要一个prefs.putInt("mode", some_int); 某处。此外,您的听众毫无用处 - 放弃它。

您正在写入默认共享首选项,因为首选项屏幕会写在那里。 “模式”只是关键 - 默认共享首选项中有一个键,您的首选项文件中有一个(名为“mode_something.xml”) - 但是您编写一个(通过首选项屏幕自动)并读取另一个(从未设置)

【讨论】:

  • 有一个带有 ListPreference 的 PreferenceActiviy,其中设置了“模式”。好吧,听者真的可以放弃,是的:-)
  • @donfuxx:我以为你是 OP :D - 你确定它是在他发布的偏好活动中设置的吗? ;)
  • @Mr_and_Mrs_D,我打印出来了,肯定设置好了。
  • @user2405469:使用getDefaultSharedPreferences() ?
  • @user2405469:不要感谢我,只需按下按钮;)
【解决方案2】:

我并没有深入研究您的代码,但在快速浏览后,以下内容引起了我的注意:

你在你的preference.xml中的ListPreference中设置这个

android:entries="@array/listArray"
android:entryValues="@array/listValues" 

但是在您的 array.xml 中,您的条目字符串数组中有 3 项,而您的 listValues 字符串数组中只有 2 项

<string-array name="listArray">
    <item>10</item>
    <item>20</item>
    <item>30</item>
</string-array>
<string-array name="listValues">
    <item>1</item>
    <item>2</item>
</string-array>

您应该添加第三项到您的 listValues 字符串数组

顺便说一句:您应该考虑重命名“listArray”,以便更清楚地知道它包含您列表的条目。所以也许称它为“listEntries”。 (记得同时更改对android:entries="@array/listEntries" 的引用)一般来说,条目是用户实际看到的,值是android 使用的。因此,例如,您的字符串数组可能类似于:

<string-array name="listEntries">
    <item>one apple</item>
    <item>two apples</item>
    <item>three apples</item>
</string-array>
<string-array name="listValues">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

【讨论】:

  • 谢谢@donfuxx - 这真的很有帮助,这样更容易理解,没有注意到丢失的项目。
【解决方案3】:

onSharedPreferenceChanged 将在您每次更改首选项时被调用,因此不要在每次更改首选项时实例化新的 SharedPreferences 对象,您需要做的是:

首先,将 SharedPreferences 设为类属性,这样您就可以在 Activity 的任何地方访问首选项:

private SharedPreferences prefs;

现在,在 onCreate() 内部调用:

prefs=PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);

最后,您的 loadPreferences() 方法应如下所示:

public void loadPreferences() {

    int layoutPref = prefs.getInt("mode", 10);
    switch(layoutPref) {
    case 10:
        setContentView(R.layout.activity_main);
        break;
    case 20:
        setContentView(R.layout.second_layout);
        break;
    case 30:
        setContentView(R.layout.third_layout);
        break;
    }

}

希望对你有帮助!

【讨论】:

  • 谢谢 rick 真的很有帮助,真的很感激 :)
  • 很高兴听到这个消息!如果对您有用,您可以将此答案标记为已接受或投票吗?谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 2015-10-22
  • 1970-01-01
相关资源
最近更新 更多