这就是我尝试向listView添加项目的方法。但不幸的是,它删除旧项目并添加新项目而不是附加到旧项目。
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView
.findViewById(R.id.list_text);
ListView lv=(ListView)findViewById(R.id.itemslistView);
final List<String> MyList = new ArrayList<String>();
final ArrayAdapter<String> adp = new ArrayAdapter<String>(MainActivity.this,
R.layout.list, MyList);
lv.setAdapter(adp);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String NewListname = editText.getText().toString();
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname,
Toast.LENGTH_LONG).show();
adp.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
有谁能说我如何添加它们?
答案 0 :(得分:2)
问题是:
您的ArrayList数据由于其内部初始化而被覆盖:
final List<String> MyList = new ArrayList<String>();
使其成为全局变量。只需在
中添加数据即可MyList.add(NewListname);
或者只是将项目添加到适配器。
adp.add(NewListname);
Toast.makeText(MainActivity.this, NewListname,
Toast.LENGTH_LONG).show();
adp.notifyDataSetChanged();
希望这有帮助。
答案 1 :(得分:0)
ArrayAdapter
有add(T obj)方法。只需致电
adp.add(NewListname);
答案 2 :(得分:0)
使用以下代码:
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname,
Toast.LENGTH_LONG).show();
adp = new ArrayAdapter<String>(MainActivity.this,
R.layout.list, MyList);
adp.notifyDataSetChanged();
代替:
MyList.add(NewListname);
Toast.makeText(MainActivity.this, NewListname,
Toast.LENGTH_LONG).show();
adp.notifyDataSetChanged();