我在我的应用程序中放置了一个微调器,我想显示5个句子/字符串,当我选择其中一个时,它会显示到编辑文本视图并同时保存到共享首选项,我甚至允许用户输入他想要的任何文本,如果他不想选择任何提供的字符串。字符串是固定的,不会被更改。我能够保存用户自己提供的文本消息,但我在编辑文本视图中显示字符串并将其保存在共享首选项中时遇到问题。请帮帮我
EditText message;
Spinner spinner;
String[] alert = { "I am in danger", "Help Me", "Watch Out", "Look For Me",
"Cover ME" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.Spin_alert_message);
spinner = (Spinner)findViewById(R.id.Spin_alert_message);
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, alert);
spinner.setAdapter(adp);
// for saving text that user can change as per need
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
message = (EditText) findViewById(R.id.et_message);
// loads the text that has been stored to SP and set it to Edit Text
message.setText(preferences.getString("autoSave", ""));
// adding addTextChangedListner() to the Edit Text View
message.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// saving text after it is changed by the user
preferences.edit().putString("autoSave", s.toString()).commit();
}
});
答案 0 :(得分:1)
好吧,首先message.setText(pos);
将在EditText中设置所选位置的写入而不是Spinner中的选定文本。为了解决这个问题:
spinner = (Spinner)findViewById(R.id.Spin_alert_message);
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, alert);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String text = (String) parent.getAdapter().getItem(position);
message.setText(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// We do... nothing! :)
}
});
其次,我不确定使用TextWatcher的解决方案是否是保存SharedPreferences中文本的最佳解决方案。但是,如果它有效,请保持这样。
你的问题有点暧昧,所以我不知道这个答案是否解决了你所有的问题。如果您需要更多帮助,请尝试更详细地描述该问题。