在无线电组下仅为一个单选按钮编写共享首选项文件

时间:2013-11-15 15:51:46

标签: android eclipse sharedpreferences

我是Android开发的新手,试图了解我们如何保存默认首选项。我有以下设置布局文件:

<RadioGroup android:id="@+id/rg" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/rb1" android:checked="true" 
    android:text="RadioButton1">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/rb2" android:text="RadioButton2" android:checked="true">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/rb3" android:text="RadioButton3">
    </RadioButton>
</RadioGroup>
    <CheckBox
        android:id="@+id/ch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_ios" />

    <CheckBox
        android:id="@+id/ch2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_android"
        android:checked="true" />

    <CheckBox
        android:id="@+id/ch3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_windows" />

我希望当用户首次打开应用程序并进入设置视图时,默认情况下应检查rb1和ch1。我在main.java文件中编写了以下代码:

PreferenceManager.setDefaultValues(this, R.xml.pref, false);

我的问题是如何为上面创建pref.xml文件?

到目前为止,我有这个:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">  
  <CheckBoxPreference android:title="Function"
                      android:defaultValue="true"
                      android:summary="ch1 should be default checked"
                      android:key="functionDefault" />
</PreferenceScreen>

xml文件中的复选框有哪些必填字段?另外如何为单选按钮创建pref.xml?

1 个答案:

答案 0 :(得分:0)

请从this链接阅读共享偏好设置。在您要使用此共享首选项的活动内,在 onCreate()

之前声明以下行
public static final String PREFS_NAME = "JUST-A-NAME";
SharedPreferences settings;

onCreate()内使用共享首选项,如下所示 -

settings = getSharedPreferences(PREFS_NAME, 0);
String myval = settings.getString("radio_value", "true");

参数中的 0 指定首选项的模式。只需浏览Android开发者网站或Google如何使用共享首选项。 到那时你会知道共享首选项按键值对工作,因此在第二行中,“radio_value”是关键。

此功能 settings.getString(...)将尝试获取键 radio_value 的当前值。如果用户是第一次打开您的应用程序,您可能需要使用默认值,即第二个参数“true”生效时。 所以默认值“true”将在字符串myval中,使用if-else条件来检查 - 取消选中你的单选按钮。如果您需要有关通过Java代码切换单选按钮的帮助,请参阅this SO post。

希望它有所帮助。

相关问题