我在偏好中有EditText,我的layout也有EditText。所以我想从Preferences中获取字符串,当我点击我的按钮时将它用于EditText。所以我试着这样:
public class MainActivity extends Activity{
SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
}
//OnClick method
public void Button(View view) {
EditText et1 = (EditText) findViewById(R.id.edittext);
String string = sharedPreferences
.getString("ime", "default");
et1.setText(String.valueOf(string));
}
和我的prefs xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference android:title="Uredi Text"
android:key="ime"
android:summary="ime pjesme"
/>
</PreferenceScreen>
每当我点击按钮时EditText文字变为“默认”
答案 0 :(得分:0)
不要直接使用getBaseContext()
- 使用“本地上下文”,在您的情况下是活动(作为activty extends Context)。因此,在您的示例代码中,将其替换为this
:
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences( this );