35

I am developing an android application in which I have made one ListView. I have to add 2 buttons with each row in ListView. These 2 buttons are Add and Delete. When user selects one of the buttons then some actions should be taken. How can I do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Looking Forward
  • 3,579
  • 8
  • 45
  • 65
  • 1
    Using custom listview layout, Add two buttons in the item view and write action on the corresponding click event – OMAK Jul 08 '13 at 11:53

3 Answers3

94

You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.

<?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/list_item_string"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:paddingLeft="8dp"
    android:textSize="18sp"
    android:textStyle="bold" /> 

<Button
    android:id="@+id/delete_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:text="Delete" /> 

<Button
    android:id="@+id/add_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/delete_btn"
    android:layout_centerVertical="true"
    android:layout_marginRight="10dp"
    android:text="Add" />

</RelativeLayout>

Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.

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.my_custom_list_layout, null);
    } 
    
    //Handle TextView and display string from your list
    TextView listItemText = (TextView)view.findViewById(R.id.list_item_string); 
    listItemText.setText(list.get(position)); 

    //Handle buttons and add onClickListeners
    Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
    Button addBtn = (Button)view.findViewById(R.id.add_btn);
    
    deleteBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            list.remove(position); //or some other task
            notifyDataSetChanged();
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            notifyDataSetChanged();
        }
    });
      
    return view; 
} 
}

Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.

public class MyActivity extends Activity { 
  
@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my_activity); 
    
    //generate list
    ArrayList<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");

    //instantiate custom adapter
    MyCustomAdapter adapter = new MyCustomAdapter(list, this);
    
    //handle listview and assign adapter
    ListView lView = (ListView)findViewById(R.id.my_listview);
    lView.setAdapter(adapter);
}
starball
  • 20,030
  • 7
  • 43
  • 238
adam83
  • 941
  • 6
  • 4
  • what If i want to use CursorLoader? – Mr. Robot Dec 18 '14 at 19:04
  • 4
    return list.get(pos).getId();---Cannot resolve method 'getId()' – Taha Körkem Feb 19 '15 at 16:30
  • 2
    @TahaKörkem just replace "return list.get(pos).getId()" with "return 0". The getId() method is not useful if your list items do not have an Id property. – adam83 Feb 19 '15 at 17:23
  • 1
    Thanks this was helpful, but there is one little problem. I can't seem to use the position variable inside those anonymous classes, it says it has to be final. – Mubashar Abbas Nov 10 '15 at 06:47
  • Can't understand.. how i can start some action on button click, wich will not connected with my list... So i need practical the same, but with some difference. I need to start download file, on the button click, and show progress.... after finished i need to have button upgrade to active (or replace progress bar) And then i will start to load file by bluetooth to my device. So i need to sent something more than list... because type of layout depend from some value (i need array[int][string], o something like that, I think)... i'm newbie for Android and Java, so it all is rather hard for me) – Dmitry Lyalin Apr 07 '16 at 13:19
  • "R.layout.my_custom_list_layout" is because that RelativeLayout is saved in a layout file called "my_custom_list_layout.xml" – Hossein Margani Oct 18 '17 at 22:05
14

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}
nikolas
  • 8,707
  • 9
  • 50
  • 70
10

Step-1: Create 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:background="#0099CC"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Multi Touch Listview"
        android:textColor="#FFFFFF"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/textView"
        android:layout_marginTop="5dp"
        android:cacheColorHint="#00000000" />

</RelativeLayout>

Step-2 Create row.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:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="User Name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="5dp"
        android:text="Address"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="16sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="#FFFFFF"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Edit Data"
        android:textColor="#0099CC" />

    <Button
        android:id="@+id/button2"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="3dp"
        android:background="#FFFFFF"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="Delete"
        android:textColor="#0099CC" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="5dp"
        android:text="Location" />

</RelativeLayout>

Step-3 Create User.java bean class

public class User {
 String name;
 String address;
 String location;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public String getLocation() {
  return location;
 }

 public void setLocation(String location) {
  this.location = location;
 }

 public User(String name, String address, String location) {
  super();
  this.name = name;
  this.address = address;
  this.location = location;
 }

}

Step-4 Create UserCustomAdapter.java

 public class UserCustomAdapter extends ArrayAdapter<User> {
     Context context;
     int layoutResourceId;
     ArrayList<User> data = new ArrayList<User>();
    
     public UserCustomAdapter(Context context, int layoutResourceId,
       ArrayList<User> data) {
      super(context, layoutResourceId, data);
      this.layoutResourceId = layoutResourceId;
      this.context = context;
      this.data = data;
     }
    
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      UserHolder holder = null;
    
      if (row == null) {
       LayoutInflater inflater = ((Activity) context).getLayoutInflater();
       row = inflater.inflate(layoutResourceId, parent, false);
       holder = new UserHolder();
       holder.textName = (TextView) row.findViewById(R.id.textView1);
       holder.textAddress = (TextView) row.findViewById(R.id.textView2);
       holder.textLocation = (TextView) row.findViewById(R.id.textView3);
       holder.btnEdit = (Button) row.findViewById(R.id.button1);
       holder.btnDelete = (Button) row.findViewById(R.id.button2);
       row.setTag(holder);
      } else {
       holder = (UserHolder) row.getTag();
      }
      User user = data.get(position);
      holder.textName.setText(user.getName());
      holder.textAddress.setText(user.getAddress());
      holder.textLocation.setText(user.getLocation());
      holder.btnEdit.setOnClickListener(new OnClickListener() {
    
       @Override
       public void onClick(View v) {
        // TODO Auto-generated method stub
        Log.i("Edit Button Clicked", "**********");
        Toast.makeText(context, "Edit button Clicked",
          Toast.LENGTH_LONG).show();
       }
      });
      holder.btnDelete.setOnClickListener(new OnClickListener() {
    
       @Override
       public void onClick(View v) {
        // TODO Auto-generated method stub
        Log.i("Delete Button Clicked", "**********");
        Toast.makeText(context, "Delete button Clicked",
          Toast.LENGTH_LONG).show();
       }
      });
      return row;
    
     }
    
     static class UserHolder {
      TextView textName;
      TextView textAddress;
      TextView textLocation;
      Button btnEdit;
      Button btnDelete;
     }
    }

Step-5 Create MainActivity.java

public class MainActivity extends Activity {
 ListView userList;
 UserCustomAdapter userAdapter;
 ArrayList<User> userArray = new ArrayList<User>();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  /**
   * add item in arraylist
   */
  userArray.add(new User("Mumer", "Spain", "Spain"));
  userArray.add(new User("Jon", "EW", "USA"));
  userArray.add(new User("Broom", "Span", "SWA"));
  userArray.add(new User("Lee", "Aus", "AUS"));
  userArray.add(new User("Jon", "EW", "USA"));
  userArray.add(new User("Broom", "Span", "SWA"));
  userArray.add(new User("Lee", "Aus", "AUS"));
  /**
   * set item into adapter
   */
  userAdapter = new UserCustomAdapter(MainActivity.this, R.layout.row,
    userArray);
  userList = (ListView) findViewById(R.id.listView);
  userList.setItemsCanFocus(false);
  userList.setAdapter(userAdapter);
  /**
   * get on item click listener
   */
  userList.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View v,
     final int position, long id) {
    Log.i("List View Clicked", "**********");
    Toast.makeText(MainActivity.this,
      "List View Clicked:" + position, Toast.LENGTH_LONG)
      .show();
   }
  });

 }

}

You may check my blog for full code. look here-

Manish Srivastava
  • 1,649
  • 2
  • 15
  • 23
  • Confusion is there. My ListView is ready. I just have to add two buttons in each row. I am not getting your code clearly. – Looking Forward Jul 08 '13 at 12:15
  • 1
    just put two button in your row_layout.xml like other textview and call them with their id.. And set onclick listner like me- holder.btnDelete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.i("Delete Button Clicked", "**********"); Toast.makeText(context, "Delete button Clicked", Toast.LENGTH_LONG).show(); } }); – Manish Srivastava Jul 08 '13 at 12:23
  • well I suggest just copy paste all code and make a demo application then you can easily understand working of code.. – Manish Srivastava Jul 08 '13 at 12:24
  • Now I have to make changes to my GUI as per requirement. I have to add two buttons only at bottom with listview. – Looking Forward Jul 09 '13 at 05:10
  • Do you have any idea about this.? – Looking Forward Jul 09 '13 at 05:15
  • Yes just put your button into relative layout where you want and call them with their ID in your layout.. See my demo.. – Manish Srivastava Jul 09 '13 at 05:22
  • Still you did not get any luck? If yes please mark this answer as correct.. I need some point at this stage :) Thanks.. – Manish Srivastava Jul 10 '13 at 07:01