我有一个带有edittext字段和添加按钮的活动设置。实质上,当用户对edittext进行更改并点击Add时,应使用edittext字段创建新的textview。此外,我希望即使在我离开屏幕或活动后,创建的文本视图也可用。我遇到的问题是,当我点击添加时,每次都会在新创建的文本视图中显示默认值,当我离开活动时,所有文本视图都会完全消失。有什么建议吗?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
etDocNote.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v1, int keyCode1, KeyEvent event1) {
if ((event1.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode1 == KeyEvent.KEYCODE_ENTER)) {
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", etDocNote.getText().toString()).commit();
return true;
}
return false;
}
});
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = getSharedPreferences("myprefs", 0).getString("etDocNote", "" );
nLayout.addView(createNewTextView(newDocNote));
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}
答案 0 :(得分:0)
所以你的问题有两部分:
以下是您需要做的:删除setOnKeyListener并将onClick()函数更改为
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String value = etDocNote.getText().toString();
nLayout.addView(createNewTextView(value));
// Save to shared preferences
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", value).commit();
}
};