ListView加checkBox可以实现全选等功能

1.效果图

2.LIteView_item布局

<?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"
    android:layout_marginRight="10dip"
    android:layout_weight="1.0"
    android:layout_marginLeft="10dp"

    android:orientation="horizontal"
    android:descendantFocusability="blocksDescendants"
    android:background="#AAAAAA"
    >

    <CheckBox android:id="@+id/isCheakBox" android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

    <ImageView android:id="@+id/dailyPic"
        android:contentDescription="dailyPic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3.0dip"
        android:src="@mipmap/txt"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"/>

    <TextView
        android:id="@+id/dailyName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/dailyPic"
        android:text=""
        android:layout_centerVertical="true"
        android:textColor="#000000"
        android:textSize="12.0sp" />

</RelativeLayout>

 
 

3.主布局: 只要有checkbox,listView 也行

<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="@color/bai"
    tools:context="myapplication.com.myblue.activity.Rizhi_Activity">
    <LinearLayout
        android:layout_height="45dp"
        android:layout_width="match_parent"
        android:background="@color/rizhi"
        android:id="@+id/layout1"
        android:visibility="gone"
        android:gravity="center_horizontal|center_vertical"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/textView_quxiao"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:text="取消"
            android:layout_marginLeft="10dp"
            android:background="@color/rizhi"
            android:gravity="center_horizontal|center_vertical"
            android:textColor="@color/bai"/>
        <TextView
            android:id="@+id/textView_quanxuan"
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:text="已选择1项"
            android:textColor="@color/bai"/>
        <CheckBox android:id="@+id/all_check_btn"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout2"
        android:layout_height="@dimen/titlebar"
        android:layout_width="match_parent"
        android:background="@color/theme"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/imageView1"
            android:layout_height="match_parent"
            android:layout_width="@dimen/zhuyemian"
            android:layout_gravity="center_vertical"
            android:src="@mipmap/search_back"/>
        <TextView
            android:id="@+id/textView1"
            android:layout_height="@dimen/titlebar"
            android:layout_width="0dp"
            android:text="@string/rizhi_textview1"
            android:gravity="center_horizontal|center_vertical"
            android:textSize="@dimen/title_size"
            android:layout_weight="1"/>
        <ImageView
            android:layout_height="match_parent"
            android:layout_width="@dimen/zhuyemian"
            android:src="@mipmap/search"/>
    </LinearLayout>

        <ListView
            android:layout_marginTop="3dp"
            android:id="@+id/listView"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_width="match_parent"/>

    <LinearLayout
        android:layout_height="45dp"
        android:layout_width="match_parent"
        android:id="@+id/layout3"
        android:visibility="gone"
        android:background="@color/rizhi"
        android:gravity="center_horizontal|center_vertical"
        android:orientation="horizontal">

        <TextView
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:text="删除"
            android:textColor="@color/bai"/>
        <TextView
            android:id="@+id/textView_loadup"
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:text="上传"
            android:textColor="@color/bai"/>

    </LinearLayout>
</LinearLayout>

4.adapter

 class DraftDailyAdapter extends BaseAdapter {

        public List<Item> list;
        private Context context;
        LayoutInflater inflater;

        public DraftDailyAdapter(Context context, List<Item> list) {
            super();
            this.list = list;
            this.context = context;
            inflater = LayoutInflater.from(this.context);
        }
        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }
        @Override
        public Object getItem(int location) {
            return list.get(location);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            Item item = list.get(position);
            //Item的位置
            final int listPosition = position;
            //这个记录item的id用于操作isCheckedMap来更新CheckBox的状态
            final int id = item.id;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.layout_listviewitem, null);
                holder.tvName = (TextView)convertView.findViewById(R.id.dailyName);
                holder.dailyPic= (ImageView) convertView.findViewById(R.id.dailyPic);
                //  holder.deleteButton = (ImageButton)convertView.findViewById(R.id.deleteAttachment);
                holder.cBox = (CheckBox)convertView.findViewById(R.id.isCheakBox);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            // Log.d(TAG, "id="+id);
            holder.cBox.setChecked(isCheckedMap.get(id));
            holder.tvName.setText(item.name);
            if(item.name.contains("txt")){
                holder.dailyPic.setImageResource(R.mipmap.txt);
            }else{
                holder.dailyPic.setImageResource(R.mipmap.photo);
            }
//            holder.deleteButton.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View paramView) {
//                    //Log.d(TAG, "deletePosition="+listPosition+"");
//                    //删除list中的数据
//                    list.remove(listPosition);
//                    //删除Map中对应选中状态数据
//                    isCheckedMap.remove(id);
//                    //通知列表数据修改
//                    adapter.notifyDataSetChanged();
//                }
//            });
            holder.cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  layout1.setVisibility(View.VISIBLE);
                  layout2.setVisibility(View.GONE);
                  layout3.setVisibility(View.VISIBLE);
                    if(isChecked){
                        isCheckedMap.put(id,true);
                    }else{
                        isCheckedMap.put(id,false);
                    }
                }
            });
            return convertView;
        }
        public final class ViewHolder {
            public TextView tvName;
            public ImageButton deleteButton;
            public CheckBox cBox;
            ImageView dailyPic;
        }
    }

5.item数据类

class Item {
        private Integer id;
        private String name;
        String address;
    }

6.实现

package myapplication.com.myblue.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import myapplication.com.myblue.R;
import myapplication.com.myblue.adapter.ListViewAdapter;
import myapplication.com.myblue.entity.WenjianBean;
import myapplication.com.myblue.utils.SDcardHelper;

public class Rizhi_Activity extends AppCompatActivity  implements SearchView.OnQueryTextListener{
    SearchView rizhi_searchview;
    ImageView imageView1;
    LinearLayout layout1,layout2,layout3;
    TextView textView_quanxuan,textView_quxiao,textView_loadup;

    /*
    *
    * ***/
    private List<Item> itemList;
    private DraftDailyAdapter adapter;
    private Map<Integer, Boolean> isCheckedMap;
    private CheckBox allCheckBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rizhi);
        initView();
    }
    public void  initView(){
       // 这里的data数据是读取的文件夹path和name,根据自己需要修改Item数据
        File file1=new File(Environment.getExternalStorageDirectory()+File.separator+"AA");
        File[] files = file1.listFiles();
        List<WenjianBean>data=SDcardHelper.getFileName(files);
        allCheckBox = (CheckBox)findViewById(R.id.all_check_btn);
        itemList = new ArrayList<Item>();
        ListView list= (ListView) findViewById(R.id.listView);
        isCheckedMap = new HashMap<Integer, Boolean>();
        //初始化数据
        for(int i=0;i<data.size();i++){
            Item item = new Item();
            item.id=i;
            item.name = data.get(i).getName();
            item.address=data.get(i).getAddress();
            itemList.add(item);
            isCheckedMap.put(i,false);
        }
        adapter = new DraftDailyAdapter(this,itemList);
        list.setAdapter(adapter);
        textView_loadup= (TextView) findViewById(R.id.textView_loadup);
        layout1= (LinearLayout) findViewById(R.id.layout1);
        layout2= (LinearLayout) findViewById(R.id.layout2);
        layout3= (LinearLayout) findViewById(R.id.layout3);
        textView_quanxuan= (TextView) findViewById(R.id.textView_quanxuan);
        textView_quxiao= (TextView) findViewById(R.id.textView_quxiao);

      //  final ListViewAdapter adapter=new ListViewAdapter(getApplicationContext(),data,layout1,layout2,layout3);
       // listView= (ListView) findViewById(R.id.listView);
      //  listView.setAdapter(adapter);
        imageView1= (ImageView) findViewById(R.id.imageView1);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        textView_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout1.setVisibility(View.GONE);
                layout2.setVisibility(View.VISIBLE);
                layout3.setVisibility(View.GONE);
            }
        });

        textView_quanxuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        /****
         * 全选功能
         * */
        allCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Set<Integer> set = isCheckedMap.keySet();
                Iterator<Integer> iterator = set.iterator();
                if(isChecked){
                    while(iterator.hasNext()){
                        Integer keyId = iterator.next();
                        isCheckedMap.put(keyId,true);
                    }
                }else{
                    while(iterator.hasNext()){
                        Integer keyId = iterator.next();
                        isCheckedMap.put(keyId,false);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });

        textView_loadup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for(Map.Entry<Integer, Boolean> entry:isCheckedMap.entrySet()){
                    System.out.println(entry.getKey()+"--->"+entry.getValue());
                    if(entry.getValue().toString().contains("true")){                //  读取选中的数据
                        System.out.println("**"+itemList.get(entry.getKey()).name+itemList.get(entry.getKey()).address);              
                    }
                }
            }
        });

    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    /***
     *  adapter
     * **/
    class DraftDailyAdapter extends BaseAdapter {

        public List<Item> list;
        private Context context;
        LayoutInflater inflater;

        public DraftDailyAdapter(Context context, List<Item> list) {
            super();
            this.list = list;
            this.context = context;
            inflater = LayoutInflater.from(this.context);
        }
        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }
        @Override
        public Object getItem(int location) {
            return list.get(location);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            Item item = list.get(position);
            //Item的位置
            final int listPosition = position;
            //这个记录item的id用于操作isCheckedMap来更新CheckBox的状态
            final int id = item.id;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.layout_listviewitem, null);
                holder.tvName = (TextView)convertView.findViewById(R.id.dailyName);
                holder.dailyPic= (ImageView) convertView.findViewById(R.id.dailyPic);
                //  holder.deleteButton = (ImageButton)convertView.findViewById(R.id.deleteAttachment);
                holder.cBox = (CheckBox)convertView.findViewById(R.id.isCheakBox);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            // Log.d(TAG, "id="+id);
            holder.cBox.setChecked(isCheckedMap.get(id));
            holder.tvName.setText(item.name);
            if(item.name.contains("txt")){
                holder.dailyPic.setImageResource(R.mipmap.txt);
            }else{
                holder.dailyPic.setImageResource(R.mipmap.photo);
            }
//            holder.deleteButton.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View paramView) {
//                    //Log.d(TAG, "deletePosition="+listPosition+"");
//                    //删除list中的数据
//                    list.remove(listPosition);
//                    //删除Map中对应选中状态数据
//                    isCheckedMap.remove(id);
//                    //通知列表数据修改
//                    adapter.notifyDataSetChanged();
//                }
//            });
            holder.cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  layout1.setVisibility(View.VISIBLE);
                  layout2.setVisibility(View.GONE);
                  layout3.setVisibility(View.VISIBLE);
                    if(isChecked){
                        isCheckedMap.put(id,true);
                    }else{
                        isCheckedMap.put(id,false);
                    }
                }
            });
            return convertView;
        }
        public final class ViewHolder {
            public TextView tvName;
            public ImageButton deleteButton;
            public CheckBox cBox;
            ImageView dailyPic;
        }
    }
// 填充数据类
    class Item {
        private Integer id;
        private String name;
        String address;
    }
}
时间: 2024-12-26 04:39:39

ListView加checkBox可以实现全选等功能的相关文章

android的listview加checkbox实现单保存checkbox的勾选信息

最近做一个项目时想要增加安卓端的一个功能,就是增加一个activity上面有很多checkbox的勾选信息,然后可以给人选择多选框,看起来还算很简单..但是真正做起来就有很多麻烦了.. 虽然我对安卓有点了解,以前也看过一些代码,但都是看别人的代码,看代码当然简单啦,这下要全部自己写,这下有点棘手了,一开始真是无从下手啊,后来去网上查了一下,觉得有个人的写法不错,就是用listview导入adapter的布局这样子,于是我就照着他的代码的原型开始改了起来. 改了N久,终于改的有点样子了,其中也花了

2016/3/30 租房子 ①建立租房子的增、删、改php页面 ②多条件查询 ③全选时 各部分全选中 任意checkbox不选中 全选checkbox不选中

字符串的另一种写法:<<<AAAA; 后两个AA回车要求定格  不然报错 例子: 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <?php 9 $str = &

2017-5-26 正则表达式,js实战(加减数量,全选)

1.正则表达式:验证数据格式的准确性. 用正则表达式判断手机号格式是否正确: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml&qu

关于列表中checkbox选中,全选/反选设置

关于列表中checkbox选中,全选设置 1 <html> 2 <head> 3 <script type="text/javascript"> 4 //点击行时,checkbox处理方法 5 function doclick(id){ 6 var allche = document.getElementById("allid");//全选checkbox 7 var che = document.getElementsByNam

jqury简易实现checkbox反选与全选

前段时间,一个同事让我帮忙写个全选与反选的功能,本来一段很简单的代码,突然卡顿,写了好几个小时,其实之前也做过类似的功能,只是一下子就懵逼了,简而言之还是自己对checkbox的反选与全选没有掌握十足,所以再利用一些时间重复巩固了这个小功能,代码不长,想到了就简单,没想到就折腾好久. 就自己遇到一些坑,关于checkbox细谈一二,今天只用jquery实现 下面是html代码 <p><label><input type="checkbox" class=&

Jquery 利用单个复选款(checkbox)实现全选、反选

1 <script type="text/javascript"> 2 $(function(){ 3 //全选 4 $("#CheckedAll").click(function(){ 5 $('[name=items]:checkbox').attr("checked", this.checked ); 6 }); 7 $('[name=items]:checkbox').click(function(){ 8 //定义一个临时变

分页的前后交互配置+全选隐藏功能,该条信息的前后交互(全选与该条信息的绑定)。

其中两个知识点需要注意: 1.分页的前后交互配置. 2.全选隐藏功能,该条信息的前后交互(全选与该条信息的绑定). a)分页的交互: $(function(){         var pageNum=1;//总页数         var pageIndex=1;//页索引,当前页         var num=10;         getData(1,num);         function getData(pageIndex,num){             $.ajax({  

JQuery实现列表中复选框全选反选功能封装

JQuery实现列表中复选框全选反选功能封装 我们在做列表的时候经常会遇到全选,反选进行批量处理问题,例如: 我当时就是简单的实现了,然后想封装到公共的js中,封装的太烂,不好意思贴出来了(就是把实现代码之间放到公共js中,然后每个页面都用固定的id,class,现在想想我都不好意思叫他封装了),然后想到之前老大有写过这个功能去看下他怎么写的,真是没有对比就没有伤害啊,这才叫封装: 1 $(':checkbox[data-check-target]').click(function () { 2

jquery 书写全选反选功能

书写一个后台管理中用到的全选反选功能.代码如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>全选反选插件</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/