我正在尝试在MainActivity中设置TextView的文本。可以在SettingsActivity中更改和设置Textview的字符串。 但不知何故,我的代码只使用默认值而不读取首选项文件...
问候
好的,所以我得到了以下
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
的preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:capitalize="words"
android:defaultValue="@string/default_name"
android:inputType="textCapWords"
android:key="Username"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/name_button" />
</PreferenceScreen>
MainActivity.java
SettingsTest = (TextView) findViewById(R.id.SettingsTestName);
. . .
SharedPreferences prefs = this.getSharedPreferences("preferences.xml", this.MODE_PRIVATE);
String name = prefs.getString("Username", "Username angeben");
SettingsTest.setText(name);
但由于某些原因,我只在TextView中获得默认值"Username angeben"
答案 0 :(得分:1)
做这样的事情:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
String nickname = prefs.getString("Username", "Username angeben");