Delete an item by clicking any item in the list

I made a listview, where in the title of the edit text box to add a list. And it works great and successfully adds the item. Then I try to call this list and install the adapter. Now I want when I click on an item that needs to be deleted, but its strength is closed. Here is my code:

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); } } 
+4
source share
1 answer

try this way

 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(); } }); 

remove from list and update list with adapter notification

edited

why do you use this operator when expanding ListActivity

 listViewCity = ( ListView ) findViewById( R.id.list); 

either you can get a ListView using getListView () with a ListActivity extension, or extend an action instead of ListActivity.

+5
source

Source: https://habr.com/ru/post/1434162/


All Articles