我制作了一个listview,在标题处有一个编辑文本字段来添加列表。它工作正常并成功添加项目。然后我尝试调用此列表视图并设置适配器。 现在我想要的是当我点击它应该被删除的项目,但它的强制关闭。这是我的代码:
public class AddDeleteItemActivity extends ListActivity {
public ListView listViewCity;
public Context ctx;
ArrayList list = new ArrayList();
ArrayAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btnAdd);
ctx=this;
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
listViewCity = ( ListView ) findViewById( R.id.list);
listViewCity.setAdapter(adapter);
listViewCity.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(getApplicationContext(), " " +position , Toast.LENGTH_LONG).show();
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
adapter.notifyDataSetChanged();
}
});
btn.setOnClickListener(listener);
setListAdapter(adapter);
}
}
答案 0 :(得分:5)
试试这种方式
listViewCity.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(getApplicationContext(), " " +position , Toast.LENGTH_LONG).show();
list.remove(position);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
}
});
从列表中删除并使用适配器通知刷新列表
<强>编辑强>
扩展ListActivity时使用此语句的原因
listViewCity = ( ListView ) findViewById( R.id.list);
您可以使用getListView()获取ListView对象,扩展ListActivity或扩展Activity而不是ListActivity。