Seleccione marcar todo en la vista de lista para marcar todas las casillas de verificación
Frecuentes
Visto 1,751 veces
1
I am having an listview with checkboxes,from the top i am giving an "select all",while check the select all,i want all checkbox has to select it.But now while checking the select all is not selecting all the checkbox.Seperate checkbox is working fine.
This is the layout for select all for listview.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:paddingRight="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/strAll"
/>
<CheckBox
android:id="@+id/chkAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</RelativeLayout>
"ContactActivity.java"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,lv);
setListAdapter(adapter);
final CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int size = 0;
boolean isChecked = chkAll.isChecked();
if (isChecked == true) {
size = lv.getCount();
for (int i = 0; i <= size; i++)
lv.setItemChecked(i, true);
} else if(isChecked==false)
{
size = lv.getCount();
for (int i = 0; i <= size; i++)
lv.setItemChecked(i, false);
}
}
});
send.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
private void setListAdapter(ArrayAdapter<String> adapter1) {
// TODO Auto-generated method stub
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
private int getCheckedItemCount(){
int cnt = 0;
SparseBooleanArray positions = lv.getCheckedItemPositions();
int itemCount = lv.getCount();
for(int i=0;i<itemCount;i++){
if(positions.get(i))
cnt++;
}
return cnt;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
4 Respuestas
2
I am posting another answer. Please listen carefully.
1.) Create a global boolean variable :-
boolean flag = false;
2.)in your getView, do this. This will not check all the checkboxes in your listview. I am assuming that you have only one checkbox in your listview.
holder.checkBoxinyourListView.setChecked(flag);
3.) Now, in the listener of the checkbox which is NO in your listview, add this code :-
checkBox not in listView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
adapter.notifyDataSetChanged();
}
});
ScreenShot 1:- When not checked
ScreenShot 2:- When Checked
This Code Works 100%
respondido 27 nov., 13:06
like this i am creating,but your are images are in horizontal i am using as vertical - Karthick M
for adapter i have to write like this ah dude final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice); setListAdapter(adapter); getListView().setAdapter(adapter); - Karthick M
images doesn't matter. horizontal doesnt matter. you do it in your vertical listview only. - Rahul Gupta
i mention above,its not working its showing some error in the above code - Karthick M
I am posting my whole code with manifest and everything. It is working. Now its upto you how you use my code in your project. After that i cannot help you more because i seriously don't know what you require. According to your question you need to select all checkbox with a checkbox outside of listview. - Rahul Gupta
1
NOTE :- In my project, i am using a lazy loader for images. Please don't get confused. Jars in my project :- universal-image-loader-1.8.7 , android-support-v4
MainActivity.Class
package com.example.listviewwithselectallcheckbxox;
//import it.sephiroth.android.library.widget.AdapterView;
//import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
//import it.sephiroth.android.library.widget.HListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class MainActivity extends Activity{
DisplayImageOptions options;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
boolean flag = false;
CheckBox selectAll;
private static final String LOG_TAG = "MainActivity";
ListView listView;
TestAdapter mAdapter;
List<RowItem> rowItems;
public static final String[] url = {"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg",
"https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
"https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg",
"https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg",
"https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg",
"https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg",
"https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
"https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg",
"https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg",
"https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s1024/Caterpillar.jpg",
"https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s1024/Chess.jpg"};
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.build();
ImageLoader.getInstance().init(config);
listView = (ListView) findViewById( R.id.hListView1 );
selectAll = (CheckBox) findViewById(R.id.selectall);
rowItems = new ArrayList<RowItem>();
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(0))
.cacheOnDisc(true)
.build();
for (int i = 0; i < url.length; i++) {
RowItem item = new RowItem(url[i]);
rowItems.add(item);
}
mAdapter = new TestAdapter(this,R.layout.list_item, rowItems);
listView.setHeaderDividersEnabled( true );
listView.setFooterDividersEnabled( true );
listView.setAdapter( mAdapter );
selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), position+"", Toast.LENGTH_SHORT).show();
CheckBox check = (CheckBox)view.findViewById(R.id.radio);
final Integer index = Integer.valueOf(position);
if(!checkedPositions.contains(index))
checkedPositions.add(index);
else
checkedPositions.remove(index);
check.setChecked(checkedPositions.contains(index));
}
});
Log.i( LOG_TAG, "choice mode: " + listView.getChoiceMode() );
}
public class TestAdapter extends ArrayAdapter<RowItem> {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
Context context;
protected ImageLoader imageLoader = ImageLoader.getInstance();
public TestAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
CheckBox radio1;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType( int position ) {
return position%3;
}
ViewHolder holder=null;
@Override
public View getView(final int position, View convertView, ViewGroup parent ) {
RowItem rowItem = getItem(position);
holder = new ViewHolder();
final int i = position;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.radio1 = (CheckBox) convertView.findViewById(R.id.radio);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.radio1.setChecked(flag);
if(flag){
if(!checkedPositions.contains(position))
checkedPositions.add(position);
}
else
{
checkedPositions.clear();
}
final Integer index = Integer.valueOf(position);
holder.radio1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if(isChecked){
if(!checkedPositions.contains(index))
checkedPositions.add(index);
}
else
checkedPositions.remove(index);
}
});
imageLoader.displayImage(rowItem.getimageUrl(), holder.imageView, options, animateFirstListener);
holder.radio1.setChecked(checkedPositions.contains(index));
return convertView;
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 5000);
displayedImages.add(imageUri);
}
}
}
}
}
RowItem.class
package it.sephiroth.listviewwithselectallcheckbxox;
public class RowItem {
private int imageId;
private String imageUrl;
public RowItem(int imageId) {
this.imageId = imageId;
}
public RowItem(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getimageUrl() {
return imageUrl;
}
public void setimageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
actividad_principal.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:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="@+id/hListView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingTop="20dip"
android:paddingBottom="20dip"
android:background="#11000000"
/>
<CheckBox
android:id="@+id/selectall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/hListView1"
android:layout_marginLeft="60dp"
android:layout_marginTop="64dp"
android:text="selectall" />
</RelativeLayout>
lista_elemento.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="ImageView"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
</ImageView>
<CheckBox
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/icon"
android:layout_marginLeft="33dp"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.sephiroth.android.sample.horizontalvariablelistviewdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
respondido 27 nov., 13:07
i am clear about this answer,i have confusion in this only one line dude mAdapter = new TestAdapter(this,R.layout.list_item, rowItems); - Karthick M
rowItems is an instance of my List type class. Basically for the urls. You can handle your own adapter in any way - Rahul Gupta
in my own adapter,i am having that one as lv only,can you come to chat lets clear the doubt - Karthick M
What is lv ? Chat on which group ?.. your adapter doesn't matter.You can use any adapter. Just focus on the checkbox code. - Rahul Gupta
,how to do seach option for name - Karthick M
0
In the getView(), Add all the position of the checkboxes
ArrayList<Integer> addIndex= new ArrayList<Integer>();//Global
checkedPositions.add(position);
This will contain all the checkboxes position
Use a ArrayList to maintain all the checkbox states in the ListView to keep track of which checkbox is checked with a boolean.
Then when you click on checkAll CheckBox you update all boolean in your list to true and do yourAdapter.notifyDataSetChanged();
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();//Global
Scenario : When Checking individual Checkboxes, adding in array list. The code below is to be added in ListView.setOnItemClickListener()
final Integer index = Integer.valueOf(position);
if(!checkedPositions.contains(index))
checkedPositions.add(index);
else
checkedPositions.remove(index);
check.setChecked(checkedPositions.contains(index));
Scenario 2 : When you check the SelectAll Checkbox.
holder.selectAllCheckbox.setOnCheckedChangeListener() listener
//Write your code here. Write an if condition that matches for the indexes in both the array list i have created and set checked as per your need
Note :- i have used an integer array list. You can use a boolean and do the same steps and the code below:-
if(list.get(position).isChecked()){
cellHolder.checkBox.setChecked(true);
}
else{
cellHolder.checkBox.setChecked(false);
}
All the boolean are at true so all the checkBoxes will be checked (the same logic goes for uncheck)
respondido 27 nov., 13:05
,how i can write the select all checkbox also in getview,because getview contains the row of the listview only na - Karthick M
where i have to put this code,what are the changes i have to do in my code - Karthick M
dude, i have mentioned every where in which listener. I cannot spoon feed. You need to understand. Do you require a code so that you can just copy and paste it and make it work ? - Rahul Gupta
Dude,can you tell me how to use search option there,to search name - Karthick M
0
public class Adapter extends ArrayAdapter<TripItem> {
private final Context context;
private final ArrayList<CommonExpenseItem> tripExpenseItems;
public TripsAdapter(Context context, ArrayList<TripItem> values,
ArrayList<CommonExpenseItem> tripExpenses) {
super(context, R.layout.expense_list_row, values);
this.context = context;
this.tripExpenseItems = tripExpenses;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.expense_list_row, parent,
false);
return rowView;
}
}
The above is a simlple custom adapter ,here i am passing values in a arrayList u can pass hashmap simply,
- Initially load all the string values in a separate hashmap or pojo obj with another value named as checkBox value as "disabled", and set the adapter ,
- Then in the getView method set the name in the text view and get the checkbox string and check the checkbox if the value is enabled or uncheck if the value is disabled.
- and also set tag the position to the checkbox, and create oncheckchange listener for the checkbox item inside the getView() and inside that method get the checkbox tag and get the respective hash map or the obj from the arrayList.
- And Change the chekcbox value as enabled and notify the data set to be changed.
- Finally for ur problem. once the checkbox in main layout is checked get the arraylist and in a for loop get the hash map or the objs and set the checkbox values to "enabled" and notify dataset changed or set a new adapter and populate in the list view. like wise u can get the solution as u required.
respondido 27 nov., 13:06
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java android checkbox or haz tu propia pregunta.
Check out the similar post stackoverflow.com/questions/19027843/… - GrIsHu
@GrIsHu i saw that one,for select all they are using seperate adapter,in my code i already use an adapter have you seen or either i want to use one more adapter for select all checkbox - Karthick M
No you can manage it in adapter only check here pastebin.com/8NMbHqRV - GrIsHu