Android ListView Bound CheckBox Implementation of the optional add-and-Remove feature (DEMO) _android

Source: Internet
Author: User
Tags gettext static class stub

ListView control is quite complex, but also in the project should be regarded as more commonly used, so wrote a small demo to say, mainly the use of custom adapter, added a lot of judgment and so on ... let's look at the effect of the implementation!

OK, let's create a new project Lvcheckbox

We first write these two layouts well, one is the main layout, there is a ListView item.xml, I believe not to say more

Activity_main.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=" Match_parent "Android:o"
rientation= "vertical" > <relativelayout android:layout_width= "match_parent" android:layout_height= "50DP" android:background= "#238286" > <textview android:layout_width= "wrap_content android:layout_height=" Wrap_ Content "Android:layout_centerinparent=" true "android:text=" ListView Bound checkbox "android:textcolor=" #fff "/> < TextView android:id= "@+id/tv_add" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : layout_alignparentright= "True" android:layout_centervertical= "true" android:layout_marginright= "17DP" Android: text= "Add" android:textcolor= "#fff"/> </RelativeLayout> <listview android:id= "@+id/listview" Android: Layout_width= "Match_parent" android:layout_height= "0DP" android:layout_weight= "1" > </ListView> < LinearlayoUT android:layout_width= "match_parent" android:layout_height= "50DP" android:orientation= "Horizontal" > <
Button android:id= "@+id/btn_detele" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:layout_marginright= "1DP" android:layout_weight= "1" android:background= "#238286" android:text= "Remove" Android: Textcolor= "#fff"/> <button android:id= "@+id/btn_select_all" android:layout_width= "Match_parent" Android: layout_height= "Match_parent" android:layout_marginleft= "1DP" android:layout_weight= "1" android:background= "# 238286 "android:text=" android:textcolor= "#fff"/> </LinearLayout> </LinearLayout>

Item.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" match_parent "
android:layout_height=" 50DP "
android:gravity=" Center_vertical "
android:orientation=" Horizontal ">
<textview
android:id=" @+id/tvtitle
" Android:layout_width= "Wrap_content"
android:layout_height= "wrap_content"
android:layout_marginleft= " 15DP "
android:layout_weight=" 7 "
android:text=" text "/>
<checkbox
android:id=" @+id/ Cbcheckbox "
android:layout_width=" wrap_content "
android:layout_height=" Wrap_content "
android: layout_weight= "1"/>
</LinearLayout>

Item.xml has only two controls, well understood.

Initializing controls

We use the Initview () method to initialize these controls

private void Initview () {
Tv_add = (TextView) Findviewbyid (r.id.tv_add);
Tv_add.setonclicklistener (this);
Btn_detele = (Button) Findviewbyid (R.id.btn_detele);
Btn_detele.setonclicklistener (this);
Btn_select_all = (Button) Findviewbyid (r.id.btn_select_all);
Btn_select_all.setonclicklistener (this);
ListView = (ListView) Findviewbyid (R.id.listview);
}

Then inherit the Click Event, Button's and ListView's

Implements Onclicklistener,onitemclicklistener

Custom Adapter

The hardest thing here is adapter.

1.Bean

We write an entity class ahead of time for the data to be recorded conveniently

Package Com.lgl.lvcheckbox;
public class Bean {
private String title;
Construct method Public
Bean (String title) {
super ();
this.title = title;
}
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
}

ListAdapter

All of this is written in a note, and it's easy for everyone to see

Package Com.lgl.lvcheckbox;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Android.content.Context;
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.CompoundButton.OnCheckedChangeListener;
Import Android.widget.TextView; /** * Custom Adapter * * @author LGL * */public class ListAdapter extends Baseadapter {//DataSet private list<bean> List = n
EW arraylist<bean> ();
Contextual private context Mcontext;
Store check box status of Map collection private Map<integer, boolean> Ischeck = new Hashmap<integer, boolean> (); Construct method public ListAdapter (context Mcontext) {super (); this.mcontext = Mcontext;//default to unchecked Initcheck (false);//Initialize map set The number of combined public void Initcheck (Boolean flag) {//Map collection and list number is consistent for (int i = 0; i < list.size (); i++) {//Set default display Isch
Eck.put (i, flag); }
//Set data public void SetData (list<bean> data) {this.list = data;}//Add data public void AddData (bean bean) {//subscript
Data list.add (0, Bean); @Override public int GetCount () {//TODO auto-generated a stub//if NULL returns a 0 return list!= null? List.size ()
: 0; @Override public Object getitem (int position) {//TODO auto-generated Method stub return List.get (position);} @Overrid E public long getitemid (int position) {//TODO auto-generated method stub return position} @Override public View Getvie
W (final int position, View Convertview, ViewGroup parent) {Viewholder viewholder = null;
View view = null; Judging is not the first time to come in if (Convertview = = null) {view = Layoutinflater.from (Mcontext). Inflate (R.layout.item, null); Viewholder = n
EW Viewholder ();
Viewholder.title = (TextView) View.findviewbyid (r.id.tvtitle);
Viewholder.cbcheckbox = (CheckBox) view. Findviewbyid (R.id.cbcheckbox);
tags, can be reused View.settag (Viewholder); else {view = Convertview;//directly bring it over with Viewholder = (Viewholder) vIew.gettag ();
//Get object bean bean = list.get (position);
Populates the Data ViewHolder.title.setText (Bean.gettitle (). toString ()); Tick-box Click event Viewholder.cbcheckbox. Setoncheckedchangelistener (New Oncheckedchangelistener () {@Override public void
OnCheckedChanged (Compoundbutton Buttonview, Boolean ischecked) {//Save Ischeck.put (position, ischecked);}) with map collection; Set state if (ischeck.get (position) = = null) {Ischeck.put (position, false);} viewHolder.cbCheckBox.setChecked (
Ischeck.get (position));
return view; }//optimize public static class Viewholder {public TextView title; public CheckBox Cbcheckbox}//All Select button Get status public map<in Teger, boolean> Getmap () {//Back to status return ischeck;//delete a data public void removedata (int position) {List.remove (posit
ION); }
}

Of course, some methods are written in the back, we write well in advance, such as delete and add something

Initializing data

We always need point data by default.

private void InitData () {
//default display data
list<bean> List = new arraylist<bean> ();
List.add (New Bean ("John"));
List.add (New Bean ("Dick"));
List.add (New Bean ("Harry"));
adapter = new ListAdapter (this);
Adapter.setdata (list);
Listview.setadapter (adapter);
}

Add data

Add Data Case
R.id.tv_add:
adapter.adddata (New Bean ("Liu Guilin"));
Notifies the refresh adapter
adapter.notifydatasetchanged ();
Break

Select All data

When we select all, the button should be all not selected, so here we have a state of

Case R.id.btn_select_all:
//Select All--All not selected
Map<integer, boolean> ischeck = Adapter.getmap ();
if (Btn_select_all.gettext (). Equals ("Select All")) {
Adapter.initcheck (true);
Notifies the refresh adapter
adapter.notifydatasetchanged ();
Btn_select_all.settext ("All do not choose");
Btn_select_all.settextcolor (Color.yellow);
} else if (Btn_select_all.gettext (). Equals ("All not Selected")) {
Adapter.initcheck (false);
Notifies the refresh adapter
adapter.notifydatasetchanged ();
Btn_select_all.settext ("Select All");
Btn_select_all.settextcolor (Color.yellow);
}
Break

Delete data

There are many factors to consider

Delete Data case
R.id.btn_detele:
//Get all
the data map<integer, boolean> ischeck_delete = Adapter.getmap ();
Gets to the number of entries, Map.size = list.size, so
int count = Adapter.getcount ();
Traversal
for (int i = 0; i < count; i++) {
//delete has two maps and list to delete, calculated
int position = i-(count-adapter.getc Ount ());
The judgement state is true to delete
if (Ischeck_delete.get (i)!= null && ischeck_delete.get (i)) {
//listview Delete Data
Ischeck_delete.remove (i);
Adapter.removedata (position);
}
Btn_select_all.settext ("Select All");
Btn_select_all.settextcolor (color.white);
Adapter.notifydatasetchanged ();
Break

Here's

int position = i-(Count-adapter.getcount ());

is a way of computing, when we delete, the array is actually rearranged, and the button is changed back to the fully selected state.

ListView's Click

We can also check the Cheakbox selected
//ListView Click event
@Override public
void Onitemclick (adapterview<?> parent , view view, int position,
long id) {
//Determine if View is the same if
(View.gettag () instanceof Viewholder) {
//if so, reuse
Viewholder holder = (viewholder) view.gettag ();
Automatic triggering of
holder.cbCheckBox.toggle ();
}

The above is a small set to introduce the Android ListView bound checkbox to achieve the full selection of Add and delete features (DEMO), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.