我是android开发的新手,遇到了一些问题。我创建了一个基于用户输入的列表视图。用户必须在对话框中输入一个类别,然后将其添加到列表中。奇迹般有效。问题是一旦用户退出应用程序并再次启动它,我如何保留这些类别?当用户启动应用程序时,列表为空白。我是否必须创建首选项屏幕或其他东西来保存用户键入的内容?这是我的代码:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity