如何在 Android Studio 中首次使用 xml 文件初始化共享首选项值



我只需要在 Android Studio 中第一次使用 .xml 文件初始化共享首选项值,我需要这些值仅在第一次读取,因为这样这些值将根据用户的需要被替换。

这是我MainActivity

public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedpreferences;
private static final String mypreference = "mypref";
private EditText mpAddress;
private EditText mPort;
private String mconfig_IpAddress;
private String mconfig_Port;
private Button mInit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);
mpAddress = (EditText) findViewById(R.id.etx_ipaddress);
mPort = (EditText) findViewById(R.id.etx_port);
mInit = (Button) findViewById(R.id.bt_init);
mInit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
leerConfigWiFiShareref();
mpAddress.setText(mconfig_IpAddress);
mPort.setText(mconfig_Port);
}
});
}
private void leerConfigWiFiShareref() {
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedpreferences.contains("SP_ConfigIpAddress")) {
mconfig_IpAddress = sharedpreferences.getString("SP_ConfigIpAddress", "");
}
if (sharedpreferences.contains("SP_ConfigPort")) {
mconfig_Port = sharedpreferences.getString("SP_ConfigPort", "");
}
}
}

我的.xml文件initial_setu.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:id="@+id/et1_ip_address"
android:key="SP_ConfigIpAddress"
android:defaultValue="192.168.4.1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789."
android:inputType="number|numberDecimal"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:textColorHighlight="#00ffffff"
android:title="IP Address" />
<EditTextPreference
android:id="@+id/et1_port"
android:key="SP_ConfigPort"
android:defaultValue="8888"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789."
android:inputType="number|numberDecimal"
android:selectAllOnFocus="true"
android:singleLine="true"
android:textColorHighlight="#00ffffff"
android:title="Port" />
</PreferenceScreen>

您已经readAgain放入false这意味着它只读取第一次。

readAgain 布尔值:是否重新读取默认值。如果为 false,则仅当过去从未调用过此方法(或者缺省值共享首选项文件中的KEY_HAS_SET_DEFAULT_VALUES为 false(时,此方法才会设置默认值。要尝试绕过此检查再次设置默认值,请将 readAgain 设置为 true。

调用此函数时,表示使用应用的默认SharedPreference

PreferenceManager.setDefaultValues(this, R.xml.initial_setup, false);
PreferenceManager.getDefaultSharedPreferences(this) // you have to use this

如果您使用自定义名称,则应尝试此操作

PreferenceManager.setDefaultValues(this, mypreference, Context.MODE_PRIVATE, R.xml.initial_setup, false);

最新更新