How to Dynamically Remove Items from Listview on a Button Click

How to dynamically remove items from ListView on a button click?

Well you just remove the desired item from the list using the remove() method of your ArrayAdapter.

A possible way to do that would be:

Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);

Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.

arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();

How to remove an item from an ListView programmatically in Android?

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, showProductsUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("products");

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
final String productId = jsonObject.getString("id");
final String productName = jsonObject.getString("productName");
HashMap<String, String> product = new HashMap<>();
product.put(ID, productId);
product.put(PRODUCT_NAME, productName);
productList.add(product);

String[] from = {ID, PRODUCT_NAME};
int[] to = {R.id.id, R.id.productName};

//NOTE: See I changed it to SimpleAdapter so you can call the notifydatasetchanged method after removing the element from the list.
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), productList, R.layout.list_products_to_buy, from, to);

ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productList.remove(position);
adapter.notifyDataSetChanged();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Delete a listview item from activity on button click from another activity

You cannot get id value to MainActivity. This line in second activity cause problem

final int id = getIntent().getExtras().getInt("id");

In Main Activity, You can put id value using name index "position"

intent.putExtra("position", id);

So you should change them to

In Second Activity

final int id = getIntent().getExtras().getInt("position");

or Main Activity

intent.putExtra("id", id);

UPDATED try this in Main Activity

intent.putExtra("id", position);

Selecting and Deleting List View items dynamically through a CAB on a button click, not through long press

This is a tricky one. I used CheckedTextView's for multiple selections inside the list however when the list scrolls the adapter re-uses the old views and sometimes checks the wrong items. To overcome that I used an array of all the currently checked items, so the adapter can know which items should be checked.

Before going back to the original list you need to call notifyDataSetChanged(), which notifies to redrawn the visible views therefore uncheck/delete the selections (depends on what action you chose back at the CAB).

package com.example.simon.cabdelete;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

/**
* Created by Simon on 2014 Jul 18.
*/

public class MainActivity extends Activity {

private final static String TAG = "MainActivity";
MyAdapter mAdapter;
ListView mListView;
List<String> mListArray;
SparseBooleanArray mCheckedItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
// Default list item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Do something on normal click
}
});

mCheckedItems = new SparseBooleanArray();
int size = 20;
mListArray = new ArrayList<String>(size);
for (int i=0; i<size; i++)
mListArray.add("Item "+i);

mAdapter = new MyAdapter(this, R.layout.list_item, mListArray);
mListView.setAdapter(mAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
break;
case R.id.action_delete:
startActionMode(new ActionBarCallBack());
break;
}
return super.onOptionsItemSelected(item);
}

public class MyAdapter extends ArrayAdapter<String> {

List<String> items;
int itemResource;
LayoutInflater inflater;

public MyAdapter(Context ctx, int resource, List<String> objects) {
super(ctx, resource, objects);
this.items = objects;
this.itemResource = resource;
this.inflater = ((MainActivity)ctx).getLayoutInflater();
}

@Override
public View getView(int pos, View convertView, ViewGroup parent) {
// (Re)Use convertView
if (convertView == null) {
convertView = inflater.inflate(itemResource, parent, false);
}
CheckedTextView checkView = (CheckedTextView) convertView;

checkView.setText(items.get(pos));

if (mCheckedItems.get(pos))
checkView.setChecked(true);
else
checkView.setChecked(false);

return convertView;
}
}

public class ActionBarCallBack implements ListView.OnItemClickListener,
ActionMode.Callback {

ActionMode actionMode;
AdapterView.OnItemClickListener previousListener;

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(TAG, "Action mode started");
actionMode = mode;
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
previousListener = mListView.getOnItemClickListener();
mListView.setOnItemClickListener(this);
mCheckedItems = new SparseBooleanArray(mListView.getCount());
return true;
}

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}

@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
Log.v(TAG, "Deleting "+mCheckedItems.size()+" items");
for (int i= mCheckedItems.size()-1; i>=0; i--) {
int key = mCheckedItems.keyAt(i);
Log.v(TAG, "Removing array item @ " + key);
mListArray.remove(key);
}
mode.finish();
return true;
default:
return false;
}
}

@Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(TAG, "Exiting action mode.");
mListView.setOnItemClickListener(previousListener);
mCheckedItems.clear();
mAdapter.notifyDataSetChanged();
}

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckedTextView checkView = (CheckedTextView) view;
boolean state = checkView.isChecked();
checkView.setChecked(!state);

if (!mCheckedItems.get(position))
mCheckedItems.put(position, true);
else
mCheckedItems.delete(position);

actionMode.setTitle(mCheckedItems.size() + " Items selected");
Log.v(TAG, "Action item @ " + position +
" clicked. It's state now is " + state);
}
}

}

And here are my xml files create the whole look:

res/layout/activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"/>
<!-- Note that drawSelectorOnTop is important as it lets
the CheckedTextViews to be clicked in a normal way too-->

</RelativeLayout>

res/layout/list_item.xml:

<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@drawable/list_selector"/>

res/drawable/list_selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/item_default" android:state_checked="false"/>
<item android:drawable="@color/item_checked" android:state_checked="true"/>
</selector>

res/values/colors.xml:

<resources>
<color name="item_default">#33B5E5</color>
<color name="item_checked">#0095CC</color>
</resources>

Delete item on ListView after click delete button on ListView

You can try using ArrayList instead as below:

 public class LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<String> data;
private static LayoutInflater inflater=null;
public ImageLoaderLogoUnder imageLoader;

public LazyAdapter(Activity a, ArrayList<String> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoaderLogoUnder(activity.getApplicationContext());
}

public int getCount() {
return data.size();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inflatelistview, null);

TextView text=(TextView)vi.findViewById(R.id.textView1);
ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
Button btn=(Button)vi.findViewById(R.id.button1);
btn.setTag(position);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
//items.remove(index.intValue());
data.remove(position);
notifyDataSetChanged();

}
});
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}

How can I attach a delete button (x) to each member of a dynamically created ListView?

User Custom Adapter with custom Layout to attach delete button to each item in listview

try this code :

CustomAdapter

public class ListAdapter extends ArrayAdapter<String> {

private int resourceLayout;
private Context mContext;
ListInterFace interface;

public ListAdapter(Context context, int resource, List<String>
items,ListInterFace interface) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.interface=interface;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;

if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}

String value= getItem(position);

if (value!= null) {
TextView tt1 = (TextView) v.findViewById(R.id.dummytext);
Button cancel_click=v.findViewById(R.id.cancel_click);

if (tt1 != null) {
tt1.setText(value);
}
//remove item on button click
cancel_click.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
interface.removeItem(position);
}
})
}

return v;
}

}

R.layout.itemlistrow defines the row of the ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy"
android:textColor="@android:color/black"
android:textSize="18sp"
android:padding="5dp"/>
<ImageView
android:id="@+id/cancel_click"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@mipmap/cancel"
android:layout_alignParentRight="true"
android:layout_margin="5dp"/>
</RelativeLayout>
</LinearLayout>

In the MainActivity define ListViewlike this,

ListView yourListView = (ListView) findViewById(R.id.itemListView);

// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, myList, new ListInterFace () {
@Override
public void removeItem( int position) {
myList.remove(position);
customAdapter .notifyDataSetChanged();
});

yourListView .setAdapter(customAdapter);

InterFace

public interface ListInterFace  {
void removeItem(int position);
}

try this link to remove item from list view on button click
Remove Item From List View On Button Click

Dynamic adding and removing elements from Widget list

I think you could use a ListView (for example with the builder constructor), so that each Row is a ListTile. The itemBuilder builds the item and you have access to the index. It would look something like this:

int itemCount = 3;
ListView.builder(
itemCount: _counter,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.radio_button_unchecked),
title: TextFormField(),
trailing: IconButton(
onPressed: () {
setState(() {
_counter--;
});
},
icon: Icon(Icons.delete),
),
);
},
),

In the setState Method in the onPressed property you have access to the index. In the example the ListView takes care to create the ListTiles based on the itemCount. You might want to create a list of objects instead of just the int itemCount to store data (maybe the text in the TextFormField). But you can still delete the item based on the index from the itemBuilder: values.deleteAt(index).

Have a look at the docs for the ListView and the ListTile classes:

https://api.flutter.dev/flutter/widgets/ListView-class.html

https://api.flutter.dev/flutter/material/ListTile-class.html



Related Topics



Leave a reply



Submit