首选项未使用 xml 中的默认值进行初始化

发布于 2024-12-23 17:28:11 字数 1704 浏览 1 评论 0原文

此问题已在本论坛中被问过多次。但我觉得它仍然需要为我清除。

public class PrefTest extends Activity {
  public Button bt_start= null;
  SharedPreferences mSharedPreferences;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.main);


    bt_start = (Button) findViewById(R.id.button1);
    bt_start.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      Log.d("TEST","");
      PreferenceManager.setDefaultValues(getApplicationContext(),
                         R.xml.settings_org, true);
      mSharedPreferences = PreferenceManager
        .getDefaultSharedPreferences(getApplicationContext());
      Boolean test = false;
      test = mSharedPreferences.getBoolean("auto_launch_key", true);
      Log.d("TEST","test = "+test);
    }
      });
    super.onCreate(savedInstanceState);
  }

  @Override
  protected void onStart() {
    super.onStart();
  }
}

在上面的代码中

   Log.d("TEST","test = "+test);

总是打印 true ,尽管我已将 xml 中的默认值设置为 false(如下所示)

 <?xml version="1.0" encoding="utf-8"?>
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="settings" >
    <CheckBoxPreference android:key="auto_launcvh_key"
        android:summaryOn="..."
        android:summaryOff="---"
        android:title="auto_launch_string" android:defaultValue="false" />
</PreferenceCategory>
 </PreferenceScreen>

我期待 setDefaultValuesXML 中获取默认值并初始化首选项。

我的理解有错吗?

This question has been asked many times in this forum. But I feel it still need to be cleared for me .

public class PrefTest extends Activity {
  public Button bt_start= null;
  SharedPreferences mSharedPreferences;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.main);


    bt_start = (Button) findViewById(R.id.button1);
    bt_start.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      Log.d("TEST","");
      PreferenceManager.setDefaultValues(getApplicationContext(),
                         R.xml.settings_org, true);
      mSharedPreferences = PreferenceManager
        .getDefaultSharedPreferences(getApplicationContext());
      Boolean test = false;
      test = mSharedPreferences.getBoolean("auto_launch_key", true);
      Log.d("TEST","test = "+test);
    }
      });
    super.onCreate(savedInstanceState);
  }

  @Override
  protected void onStart() {
    super.onStart();
  }
}

In the above code

   Log.d("TEST","test = "+test);

always prints true , though I have set default value in xml as false(as below)

 <?xml version="1.0" encoding="utf-8"?>
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="settings" >
    <CheckBoxPreference android:key="auto_launcvh_key"
        android:summaryOn="..."
        android:summaryOff="---"
        android:title="auto_launch_string" android:defaultValue="false" />
</PreferenceCategory>
 </PreferenceScreen>

Am expecting the setDefaultValues to take the defaults values form the XML and initialize the preference.

Am I wrong in my understanding?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花开半夏魅人心 2024-12-30 17:28:11

更新

经过仔细检查,我发现您可能没有正确检索SharedPreference对象。虽然我还没有尝试过,但要使此测试工作,我假设您必须调用 getSharedPreferences (String name, int mode) 与您的 XML 文件的名称,以获取存储在您的 XML 文件中定义的值的对象XML 文件。

getDefaultSharedPreferences(上下文上下文) 状态:

获取一个 SharedPreferences 实例,该实例指向默认文件
由给定上下文中的偏好框架使用。参数

context 需要其值的首选项的上下文。
返回

可用于检索和侦听的 SharedPreferences 实例
偏好的值。

您的文件似乎不是默认文件,因此您尝试调用的首选项不存在。

一般来说,处理首选项的方法是对 PreferenceActivity 进行子类化,它将创建一个首选项界面,但我很感激您只是尝试编写一个简单的测试。

另外,我假设 CheckBoxPreference android:key="auto_launcvh_key" 是编写问题时的拼写错误。我想我在第一次写这个答案时检查了密钥,它是 CheckBoxPreference android:key="auto_launch_key"

ORIGINAL

首先我会更改 test = mSharedPreferences.getBoolean( "auto_launch_key", true);test = mSharedPreferences.getBoolean("auto_launch_key", false); 如果现在返回 false,则系统中不存在该首选项,因此您的环境存在问题。尝试清理项目并重新安装。

其次在文档中它指出

readAgain - 是否重新读取默认值。注意:这不会
将首选项重置回默认值。为此
功能,使用 getDefaultSharedPreferences(Context) 并清除它
随后调用此方法并将此参数设置为 true。

因此,如果系统中已经存在该首选项,则不会覆盖该首选项,因此重新安装也应该解决此问题。或者您可以尝试在 mSharedPreferences 上调用 clear(),然后调用 PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.settings_org, true);

如果这不起作用,您可以发布完整的 XML。

UPDATE

On closer inspection I can see you probably aren't correctly retrieving the SharedPreference object. although I have not tried it, to make this test work I assume you would have to call getSharedPreferences (String name, int mode) with the name of your XML file to get the object which stores the values defined in your XML file.

getDefaultSharedPreferences (Context context) states:

Gets a SharedPreferences instance that points to the default file that
is used by the preference framework in the given context. Parameters

context The context of the preferences whose values are wanted.
Returns

A SharedPreferences instance that can be used to retrieve and listen
to values of the preferences.

Your file doesn't seem to be the default file and thus the preferences you are trying to call don't exist.

Generally the way to deal with preferences is to sub class a PreferenceActivity which will create a preferences interface but I appreciate you are just trying to write a simple test.

Also I assume the CheckBoxPreference android:key="auto_launcvh_key"is a typo when writing the question. I think I checked the key when first writing this answer and it was CheckBoxPreference android:key="auto_launch_key"

ORIGINAL

Firstly I would change test = mSharedPreferences.getBoolean("auto_launch_key", true); to test = mSharedPreferences.getBoolean("auto_launch_key", false); if it now returns false then the preference doesn't exist in the system so there is a problem with your environment. Try cleaning the project and re-installing.

Secondly in the docs it states

readAgain - Whether to re-read the default values. Note: this will NOT
reset preferences back to their default values. For that
functionality, use getDefaultSharedPreferences(Context) and clear it
followed by a call to this method with this parameter set to true.

Therefore if the preference already exists in the system as true this will not overwrite and so a re-installation should sort this out as well. or you could try calling clear() on mSharedPreferences and then calling PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.settings_org, true);

If this doesn't work can you post complete XML.

月亮是我掰弯的 2024-12-30 17:28:11

答案其实很简单。
首选项文件中的布尔值仅在为 true 时才出现,因此在读取布尔值时,您需要将默认值设置为 false:

test = mSharedPreferences.getBoolean("auto_launch_key", false);

因此,当 xml 中的首选项为 true 时,它​​会读取 true,否则使用 getBoolean 的默认值。我注意到在调试时没有任何以 false 为值的布尔首选项。

The answer is actually very simple.
Boolean values in a preference file are only present when they are true so when reading the boolean value you need to set default value to false:

test = mSharedPreferences.getBoolean("auto_launch_key", false);

So when the preferences in xml is true it reads true and otherwise uses the default of getBoolean. I noticed while debugging there aren't any Boolean preferences with false as the value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文