Android how to identify item in listview with checkbox
This is XML for Custom Row in ListView :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/camera_icon" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
This is Complete Activity in which List is implemented :
Just Copy this Activity for test then understand code. Place one listview in main Activity
package com.DemoTest;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomList extends Activity implements OnClickListener
{
ListView listView;
ArrayList<EachRow> list=new ArrayList<CustomList.EachRow>();
EachRow each;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] color={"red","green","blue","white","yellow","cyan","purple","grey",
"0red","0green","0blue","0white","0yellow","0cyan","0purple","0grey",
"1red","1green","1blue","1white","1yellow","1cyan","1purple","1grey"};
for(String str : color)
{
each=new EachRow();
each.text=str;
list.add(each);
}
listView=(ListView)findViewById(R.id.listView1);
listView.setAdapter(new MyAdapter(this, 0, list));
//listView.setOnItemClickListener(this);
}
class MyAdapter extends ArrayAdapter<EachRow>
{
LayoutInflater inflat;
ViewHolder holder;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<EachRow> objects)
{
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
inflat=LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
convertView=inflat.inflate(R.layout.row_checkox, null);
holder=new ViewHolder();
holder.textView=(TextView)convertView.findViewById(R.id.textView1);
holder.image=(ImageView)convertView.findViewById(R.id.imageView1);
holder.check=(CheckBox)convertView.findViewById(R.id.checkBox1);
holder.check.setOnClickListener(CustomList.this);
convertView.setTag(holder);
}
holder=(ViewHolder) convertView.getTag();
EachRow row= getItem(position);
Log.d("size", row.text);
holder.textView.setText(row.text);
holder.check.setChecked(row.checkBool);
holder.check.setTag(position);
return convertView;
}
@Override
public EachRow getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
private class ViewHolder
{
TextView textView;
ImageView image;
CheckBox check;
}
}
private class EachRow
{
String text;
boolean checkBool;
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
EachRow row=list.get((Integer)v.getTag());
row.checkBool=!row.checkBool;
Log.d("item", "Item Click at "+(Integer)v.getTag()+" : "+row.text+" is "+row.checkBool);
}
}
Get checked items from ListView with check box
boolean bulkflag = false;
ListView reportslistview = (ListView) findViewById(android.R.id.list);
public class MyAdapter extends SimpleAdapter {
//private List<Table> tables;
SharedPreferences prefs;
private Activity activity;
String val = "";
//@SuppressWarnings("unchecked")
public MyAdapter(Activity context, List<? extends Map<String, String>> tables, int resource, String[] from,
int[] to) {
super(context, tables, resource, from, to);
//this.tables = (List<Table>) tables;
activity = context;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.reports_list, null);
}
final CheckBox cBox=(CheckBox)row.findViewById(R.id.cb1);
if(bulkflag)
{
cBox.setVisibility(View.VISIBLE);
}
else
{
cBox.setVisibility(View.GONE);
}
cBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(cBox.isChecked())
{
selectedIds.add(recIdArr.get(reportslistview.getPositionForView(cBox)));
//System.out.println("position "+reportslistview.getPositionForView(cBox));
}
else
{
selectedIds.remove(recIdArr.get(reportslistview.getPositionForView(cBox)));
}
}
});
return row;
}
}
Checking ====>
for(int i=0;i<selectedIds.size();i++)
{
System.out.println("delete multiple"+selectedIds.size()+" "+Integer.parseInt(selectedIds.get(i)));
}
Declare selectedIds
as a global variable
Listview items with checkbox checked at start
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Android: Identify listviewItem when checkbox of item is checked/unchecked
If you only have a checkbox, you can use the OnItemClick listener that gives you position besides the view, but with this solution you have to update the checkbox manually so it doesnt consume the item click.
Another way is to use setTag(position) on the views you supply when binding.
You should consider moving on to RecyclerView.
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
How to display checkbox on every entry in a listView
You have to use a BaseAdapter and some Getter/Setter methods to add multiple texts/images/other UI elements in each item of your list view.
You have to implement multiple things to get this result. Here they are --
- Create a Custom Layout for each item of your ListView.
listview_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/layout_textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginRight="5dip"
android:textStyle="bold"/>
<TextView
android:id="@+id/layout_textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginLeft="5dip"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox"
android:text="Test"/>
</LinearLayout>
- Create a custom class and add some Getter/Setter methods.
ListRowItem.java
public class ListRowItem implements Serializable{
String carrier,number;
public String getCarrier(){
return carrier;
}
public String getNumber(){
return number;
}
public void setCarrier(String ba_carrier){
carrier = ba_carrier;
}
public void setNumber(String ba_number){
number = ba_number;
}
}
Create a custom class and extend the BaseAdapter class.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<ListRowItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<ListRowItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return this.listitem.size();
}
@Override
public Object getItem(int position) {
return this.listitem.get(position);
}
@Override
public long getItemId(int position) {
return (long) position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
String str_number = currentlistitem.getNumber();
carrier.setText(str_carrier);
number.setText(str_number);
return vi;
}
}Finally, populate your ArrayList and set the Adapter in your MainActivity.
ArrayList<ListRowItem> listitem = new ArrayList<>();
Context context = TestActivity.this;
MyBaseAdapter baseAdapter;
ListRowItem lr = new ListRowItem();
lr.setNumber(number);
lr.setCarrier(carrier);
listitem.add(lr);
baseAdapter = new MyBaseAdapter(context,listitem);
setContentView(R.layout.activity_test);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
Hope this helps!!
Selecting All Items in a Listview on checkbox select
for ( int i=0; i < listview.getChildCount(); i++) {
listview.setItemChecked(i, true);
}
Related Topics
When Should I Recycle a Bitmap Using Lrucache
Pcm -> Aac (Encoder) -> Pcm(Decoder) in Real-Time with Correct Optimization
How to Get Canonical Id from Gcm
Why Do Listview Items Not Grow to Wrap Their Content
Flutter: How to Fix "A Renderflex Overflowed by Pixels " Error
Android Rxjava 2 Junit Test - Getmainlooper in Android.Os.Looper Not Mocked Runtimeexception
How to Create Android Project with Gradle from Command Line
How Mdpi, Hdpi, Xhdpi Folder Works
Android Dialog: Removing Title Bar
Getting Error "Gradle Dsl Method Not Found: 'Compile()'" When Syncing Build.Gradle
Add Support Library to Android Studio Project
Bottomsheetdialog with Transparent Background
How to Add a Button at The End of Recyclerview
Onpagefinished() Never Called (Webview)!
Android App Installation Failed: Package Com.My.App Has No Certificates at Entry Androidmanifest.Xml