Listview with Add and Delete Buttons in Each Row in Android

How to create Listview items + Button in each row?

You have to create a custom layout xml which having a single item then you will add your button to this layout along with any other items.

CustomLayout.Xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />

</RelativeLayout>

Now after creating custom item layout you need listview which holds all items.

MainActivity.xml

.
.
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
.
.

Now in java file just set adapter with our custom layout xml

.
.
list = new ArrayList<String>(Arrays.asList("111,222,333,444,555,666".split(",")));
listview.setAdapter(new MyCustomAdapter(list, context) );
.
.

Custom adapter Class

public class MyCustomAdapter extends BaseAdapter implements ListAdapter { 
private ArrayList<String> list = new ArrayList<String>();
private Context context;

public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}

@Override
public int getCount() {
return list.size();
}

@Override
public Object getItem(int pos) {
return list.get(pos);
}

@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.CustomLayout, null);
}

//Handle TextView and display string from your list
TextView tvContact= (TextView)view.findViewById(R.id.tvContact);
tvContact.setText(list.get(position));

//Handle buttons and add onClickListeners
Button callbtn= (Button)view.findViewById(R.id.btn);

callbtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something

}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
.
}
});

return view;
}
}

Deleting a row from a ListView using Button associated with it

First Method: You describe like that

public class CustomAdapter extends CursorAdapter {

TextView task,daate;
Button del;
public static int id;
Context ct;
public CustomAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ct=context;
return LayoutInflater.from(context).inflate(R.layout.adapter, parent, false);

}

@Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
task = (TextView) view.findViewById(R.id.dynamicTask);
daate = (TextView) view.findViewById(R.id.dynamicDate);
id=cursor.getInt(cursor.getColumnIndex("_id"));
String Task=cursor.getString(cursor.getColumnIndex("task"));
String Daate=cursor.getString(cursor.getColumnIndex("ddate"));
task.setText(Task);
daate.setText(Daate);
final DatabaseHelper help=new DatabaseHelper(ct);
del = (Button) convertView.findViewById(R.id.deleteBtn);
}}

MainActivity:

public class MainActivity{
private CustomAdapter cursorAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cursorAdapter = new CustomAdapter(this, null);
}
public void deleteRecordWithId(View view) {
View parentRow = (View) view.getParent().getParent();
ListView listView = (ListView) view.getParent().getParent().getParent();
int position = listView.getPositionForView(parentRow);
long id = cursorAdapter.getItemId(position);

SQLiteDatabase db=this.getWritableDatabase();
long rows=db.delete(TABLE_NAME,"_id=?",new String[] {String.valueOf(id)});
if(rows>0) {
return true;
}
else {
return false;
}
}
}

and xml like that:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/task_outer_container"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center_vertical"
android:background="@drawable/background_transparent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:clipChildren="false"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:id="@+id/delete_button"
android:onClick="deleteRecordWithId"
app:srcCompat="@drawable/remove_icon"
android:background="@drawable/background_transparent"
android:layout_gravity="center_vertical"
android:adjustViewBounds="false"
android:paddingStart="7dp"
android:paddingEnd="7dp"
android:layout_marginEnd="-5dp"/>

</RelativeLayout>

Second Method: You should not use getView in the Cursoradapter. You need to do all the operations in bindview. So uou can not reach id with getview.

For example: https://github.com/rodoggx/w4d1_Simple_CursorAdapter/blob/master/app/src/main/java/com/example/sqlitecursoradapter/CustomAdapter.java

Add delete button in custom Listview

 public class CustomAdapter extends ArrayAdapter<String>
{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}

public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
tv.setText(s1[position]);

Button bt = (Button) v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click

bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = (int)v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove);
notifyDataSetChanged(); //remove the item
}
});

return v;
}

public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(position);
String[] s = new String[a.size()];
s=a.toArray(s);
s1 = s;
notifyDataSetChanged(); //refresh your listview based on new data

}
public int getCount() {
return s1.length;
}
public String getItem(int position) {
return s1[position];
}}

Adding a remove button to each listView element

For you list item you are using standard layout from the framework:

android.R.layout.simple_list_item_1

There's no button.

Create you custom layout with a button "Delete" instead.

But actually you don't even need button - you can click right on you list item to delete it itself.

Look for info about OnItemClickListener.

Here is pretty good tutorial:

http://www.vogella.com/tutorials/AndroidListView/article.html

Upd:

Add to your code method, something like:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

listItems.remove(position);
adapter.notifyDataSetChanged();

}

Adding a button to each row of a list view in android?

The simplest solution is you should change your String[] name to ArrayList<String> name

public class RoleList extends ArrayAdapter<String>{
//private String[] name;
private ArrayList<String> name;

// it show how many items are in the data set represented by this Adapter.
@Override
public int getCount(){
return name.size();
}
}

Current you use String[], and the size of it is fix

String[] toppings = new String[10];
System.out.println("Hello World"+toppings.length); // will print 10

therefore your ListView always display 10 items (even some is empty)

But if you use ArrayList<String>, the size of list auto change when you add or remove item then your ListView will have total row = list size

OR if you still want to use String[]
You can create a new int variable like realTotalFriends (it start from 0) and every time you add new user (just increase it by 1)

Then inside getCount() you return realTotalFriends

     int realTotalFriends;
@Override
public int getCount(){
return realTotalFriends;
}

Hope this help

Delete Button In CustomAdapter ListView

Make a Callback interface to solve your problem. I think this the best way what you want to achieve.

  1. OnItemClickListener

    public class OnItemClickListener implements View.OnClickListener {
    private int position;

    private OnItemClickCallback onItemClickCallback;

    public OnItemClickListener(int position, OnItemClickCallback
    onItemClickCallback) {
    this.position = position;
    this.onItemClickCallback = onItemClickCallback;
    }

    @Override
    public void onClick(View view) {
    onItemClickCallback.onItemClicked(view, position);
    }

    public interface OnItemClickCallback {
    void onItemClicked(View view, int position);

    }
    }
  2. In your adapter class

    private OnItemClickListener.OnItemClickCallback onItemClickCallback;
    public CustomAdapter(@NonNull Context context, ArrayList<listClass> arr,
    OnItemClickListener.OnItemClickCallback onItemClickCallback)
    {
    super(context,R.layout.detail, arr);
    this.arr = new ArrayList<listClass>(0);
    this.onItemClickCallback = onItemClickCallback;
    this.arr.addAll(arr);

    }

and

     holder.imageButton.setOnClickListener(new OnItemClickListener(position, 
onItemClickCallback));

  1. In your activity

    private OnItemClickListener.OnItemClickCallback 
    onItemDeleteClickCallback = new
    OnItemClickListener.OnItemClickCallback() {

    @Override
    public void onItemClicked(View view, int position) {

    //here you will get delete item pos

    }
    };

and

 CustomAdapter adapter = new CustomAdapter(MainActivity.this, arr, 
onItemDeleteClickCallback );
final ListView lv = findViewById(R.id.vishulv);
lv.setAdapter(adapter);

Hope this will help you.

How to add two buttons in listview

Please refer the below post it may be exactly what you want

ListView with Add and Delete Buttons in each Row in android

Hope this helps you.



Related Topics



Leave a reply



Submit