我目前有这段代码在列表视图中显示所选项目:
public class DisplayOrder extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_order);
bar();
Button btn = (Button) findViewById(R.id.btnHome);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(DisplayOrder.this, Options.class);
startActivity(myIntent);
}
});
}
private void bar() {
ListView lv = (ListView) findViewById(R.id.listViewDisplay);
List<String> itemsOrdered = new ArrayList<String>();
for (Map.Entry<Item, Integer> entry : Datastore.currentTable.getOrder().getItems().entrySet()) {
itemsOrdered.add((entry.getKey().name) + " x " + String.valueOf(entry.getValue()) + " £" + (entry.getKey().price * entry.getValue()));
}
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_display_order, R.id.textView8, itemsOrdered);
lv.setAdapter(arrayAdapter);
}
}
我想要做的是,当我点击其中一个项目时,要将其删除,但我不知道该怎么做。任何指导都将非常感谢。
答案 0 :(得分:0)
您应该通过ListView
检测点击setOnItemClickListener
的每个项目的时间
然后在这个方法中,只需删除list datasource和notifyDataSetChanged
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView < ? > parent, View view,int position, long id) {
itemsOrdered.remove(position); // remove item at index in list datasource
arrayAdapter.notifyDataSetChanged(); // call it for refresh ListView
Toast.makeText(getApplicationContext(), "remove item at " + position, Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
您必须像这样覆盖侦听器“setOnItemClickListener”:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
itemsOrdered.remove(item);
arrayAdapter.notifyDataSetChanged();
}
});
此代码从列表中删除了ítem,但您必须通知适配器的更改。当通知适配器时,列表视图会更新。