Android Real-time tutorial-51st Gun (ListView Dynamic Display and hide of child controls, checkbox Select All and reverse)

Source: Internet
Author: User

Previous time wrote an article: Android Combat Simple Tutorial-the 47th Gun (ListView multiple selection-to achieve a point meal system) Some students message suggestions, can be dynamic control checkbox display and select the anti-select function, I studied a bit, found the implementation is relatively easy, close this article. Learning is to have divergent thinking, to extrapolate, we can also adapt according to my example, add and remove some features, so you can improve your knowledge of the understanding! Let's take a look at the code:

1.main.xml:

<?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 "android:orientation=" vertical " > <listview android:id= "@+id/drink_list" android:layout_width= "Match_parent" Android:lay        out_height= "Match_parent" android:layout_above= "@+id/ll_btns" > </ListView> <linearlayout Android:id= "@+id/ll_btns" android:layout_width= "match_parent" android:layout_height= "58DP" Android Oid:layout_alignparentbottom= "true" android:orientation= "horizontal" > <button android:id= " @+id/btn_commit "android:layout_width=" wrap_content "android:layout_height=" 58DP "Android            : text= "OK"/> <button android:id= "@+id/btn_select" android:layout_width= "Wrap_content" android:layout_height="58DP" android:text= "order"/> <button android:id= "@+id/btn_select_all" Androi D:layout_width= "Wrap_content" android:layout_height= "58DP" android:text= "Select All"/> <butt On android:id= "@+id/btn_select_cancel" android:layout_width= "Wrap_content" android:layout _height= "58DP" android:text= "Reverse selection"/> </LinearLayout></RelativeLayout>
2.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=" match_parent "android:background=" #ffffff " android:orientation= "Horizontal" > <checkbox android:id= "@+id/check_box" android:layout_width= "Wra        P_content "android:layout_height=" Wrap_content "android:clickable=" false "android:focusable=" false " Android:focusableintouchmode= "true"/> <imageview android:id= "@+id/food_imager" android:layou T_width= "50DP" android:layout_height= "50DP" android:background= "#ffffff"/> <textview androi        D:id= "@+id/food_name" android:layout_width= "100DP" android:layout_height= "50DP" android:text= "Coffee" Android:gravity= "center_vertical" android:layout_marginleft= "10DP" android:textsize= "18sp"/> < TextView Android:layout_widtH= "Wrap_content" android:layout_height= "50DP" android:text= "Price: $" android:paddingleft= "20DP"         Android:textsize= "12SP"/> <textview android:id= "@+id/price" android:layout_width= "Wrap_content" android:layout_height= "50DP" android:paddingright= "10DP" android:text= "Android:layout_mar" ginleft= "20DP" android:textsize= "18SP"/></linearlayout>
3.javabean:

Package Com.example.info;public class Food {public int food_img;public string Food_name;public string Food_price;public S Tring Text;public int getfood_img () {return food_img;} public void setfood_img (int food_img) {this.food_img = food_img;} Public String Getfood_name () {return food_name;} public void Setfood_name (String food_name) {this.food_name = Food_name;} Public String Getfood_price () {return food_price;} public void Setfood_price (String food_price) {this.food_price = Food_price;} Public food (int food_img, string food_name, String food_price) {super (); this.food_img = Food_img;this.food_name = Food_na Me;this.food_price = Food_price;} Public food () {super ();} @Overridepublic String toString () {return super.tostring ();}}

4.mylistviewadapter.java:

Package Com.example.adapter;import Java.util.arraylist;import Java.util.hashmap;import Com.example.info.Food; Import Com.example.listviewselectitem.r;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.imageview;import Android.widget.textview;public class Mylistviewadapter extends BaseAdapter {// The Listprivate arraylist<food> foodlist;//that populates the data is used to control the check state of the checkbox private static Hashmap<integer, boolean> isselected;//Context Private context context;//used to import layouts private layoutinflater Inflater = null;private Boolean isshow=false;// Constructor public Mylistviewadapter (arraylist<food> list, context Context,boolean isshow) {this.context = context; This.foodlist = List;inflater = Layoutinflater.from (context); isSelected = new Hashmap<integer, boolean> (); this.isshow=isshow;//Initialize Data initdate ();} Initialize isselected data private void Initdate () {for(int i = 0; i < foodlist.size (); i++) {getisselected (). Put (I, false);}} @Overridepublic int GetCount () {return foodlist.size ();} @Overridepublic Object getItem (int position) {return foodlist.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = = null) {//Get Viewholder Object holder = new Viewholder ();//import layout and assign value to Convertviewconvertview = Inflater.inflate (R.layout.item, NULL); Holder.imageview = (ImageView) Convertview.findviewbyid (r.id.food_imager); holder.txt1 = (TextView) Convertview.findviewbyid (r.id.food_name); holder.txt2 = (TextView) Convertview.findviewbyid (r.id.price); HOLDER.CB = (CheckBox) Convertview.findviewbyid (R.id.check_box);//Set label for View Convertview.settag (holder);} else {//Remove Holderholder = (viewholder) Convertview.gettag ();} Get data food food = foodlist.get (position);//populate the data into the corresponding control of the current Convertview if (isshow) {holder.cb.setVisibility (View.visiBLE);} else {holder.cb.setVisibility (view.gone);} Holder.imageView.setImageResource (food.food_img); Holder.txt1.setText (food.food_name); Holder.txt2.setText ( Food.food_price)///Set the display of TextView in list//Set the checkbox's check status according to IsSelected holder.cb.setChecked (getisselected (). Get ( position)); return Convertview;} public static Hashmap<integer, boolean> getisselected () {return isSelected;} public static void Setisselected (Hashmap<integer, boolean> isSelected) {mylistviewadapter.isselected = isSelected;} public static class Viewholder {public TextView txt1;public TextView txt2;public ImageView imageview;public CheckBox CB;} }

5.mainactivity.java:

Package Com.example.listviewselectitem;import Java.util.arraylist;import Java.util.hashmap;import Com.example.adapter.mylistviewadapter;import Com.example.adapter.mylistviewadapter.viewholder;import Com.example.info.food;import Android.app.activity;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.window;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.button;import Android.widget.CheckBox; Import Android.widget.listview;import Android.widget.toast;public class Mainactivity extends Activity implements Onclicklistener, Onitemclicklistener {private ListView listview;private Button OK, Mselectbutton, Mselectallbutton, Mcancelallbutton;private arraylist<food> foods = new arraylist<food> ();p rivate mylistviewadapter adapter; Private CheckBox checkbox;private int checknum; RememberNumber of items selected private arraylist<string> list;private Boolean isshow = false;private Handler Handler = new Handler () {Publi c void Handlemessage (Android.os.Message msg) {if (msg.what = = 1) {adapter = new Mylistviewadapter (Foods, Getapplicationcon Text (), true); Listview.setadapter (adapter); isshow = True;mcancelallbutton.setvisibility (view.visible); Mselectallbutton.setvisibility (view.visible);} else if (Msg.what = = 0) {adapter = new Mylistviewadapter (foods, Getapplicationcontext (), false); Listview.setadapter ( adapter); isshow = False;mcancelallbutton.setvisibility (View.gone); mselectallbutton.setvisibility (View.GONE);}};}; protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title); Setcontentview (R.layout.activity_main); Initview ();//Initialize control view view = Layoutinflater.from (this). Inflate (R.layout.item, null), checkbox = (checkbox) View.findviewbyid (R.id.check_box); InitData ();// Initialize virtual data adapter = new Mylistviewadapter (Foods, GetaPplicationcontext (), false); isshow = False;listview.setadapter (adapter);} /** * Initialize control */public void Initview () {listview = (ListView) Findviewbyid (r.id.drink_list);//ListView List Control OK = (Button) fin Dviewbyid (r.id.btn_commit);//OK button list = new arraylist<string> (); Mselectbutton = (Button) Findviewbyid (r.id.btn _select) Mselectallbutton = (Button) Findviewbyid (r.id.btn_select_all); Mcancelallbutton = (Button) Findviewbyid ( R.id.btn_select_cancel); Mselectallbutton.setonclicklistener (this), Mcancelallbutton.setonclicklistener (this); if (isshow) {Mselectbutton.settext ("Cancel"); Mcancelallbutton.setvisibility (view.visible); Mselectallbutton.setvisibility ( view.visible);} else {Mselectbutton.settext ("Order Meal"); mcancelallbutton.setvisibility (View.gone); Mselectallbutton.setvisibility ( View.gone);} Mselectbutton.setonclicklistener (This), Ok.setonclicklistener (This), Listview.setonitemclicklistener (this);} /** * Initialize virtual data */public void InitData () {Class CLS = r.drawable.class;//reflection try {foods.add (new food (CLS.GETDECLARedField ("D1"). GetInt (null), "Kiwi Juice", "ten")) Foods.add (new Food (Cls.getdeclaredfield ("D2"). GetInt (null), "Orange Juice", "12") ); Foods.add (new Food (Cls.getdeclaredfield ("D3"). GetInt (null), "Beer", "(") "), Foods.add (new food (Cls.getdeclaredfield ("D4"). GetInt (null), "Grape Juice", "ten"), Foods.add (new Food (Cls.getdeclaredfield ("D5"). GetInt (NULL), "Pure wheat Milk Tea", "8"); Foods.add (new Food (Cls.getdeclaredfield ("D6") getInt (null), "Mint Juice", "ten"), Foods.add (new food (Cls.getdeclaredfield ( "D7"). GetInt (null), "Lemon Mint", "n")), Foods.add (new Food (Cls.getdeclaredfield ("D8"). GetInt (null), "Coconut Juice", "10"); Foods.add (new Food (Cls.getdeclaredfield ("D9") getInt (null), "Pearl milk Tea", "9"), Foods.add (new food (Cls.getdeclaredfield ( "D10"). GetInt (null), "Pomegranate Juice", "ten")); for (int i = 0; i < foods.size (); i++) {List.add ("data" + "+ i);};} catch (Exception e) {e.printstacktrace ();}} /** * button's Click event handling */@Overridepublic void OnClick (View v) {int mID = V.getid (); switch (MID) {case r.id.btn_commit:myprice (); /Calculate Total price and output break;case R.id.btn_select:if (isshow) {MeSsage message = Message.obtain (); message.what = 0;handler.sendmessage (message); Mselectbutton.settext ("Ordering");} else {Message message = Message.obtain (); message.what = 1;handler.sendmessage (Message); Mselectbutton.settext ("Cancel");} Break;case r.id.btn_select_all://traverse the length of the list, set the map value in Myadapter to truefor (int i = 0; i < list.size (); i++) {Mylistviewa Dapter.getisselected (). Put (I, true);} The number is set to the length of list checknum = List.size ();//Refreshes the display of the ListView and TextView adapter.notifydatasetchanged (); Break;case R.id.btn_ select_cancel://traverse the length of the list and set the map value in Myadapter to truefor (int i = 0; i < list.size (); i++) { Mylistviewadapter.getisselected (). Put (I, false);} The number is set to the length of list checknum = List.size ();//Refreshes the display of the ListView and TextView adapter.notifydatasetchanged (); break;}} /** * Method of calculating the total price */public void Myprice () {hashmap<integer, boolean> map = mylistviewadapter.getisselected (); String str = ""; int money = 0;for (int i = 0; I < map.size (); i++) {if (Map.get (i)) {str + = (i + ")", Money + = Integer.parseint (Foods.get (i). Food_Price);}} Mylistviewadapter.getisselected (). Get (""); Toast.maketext (Getapplicationcontext (), "+ str +" is selected, the total Price is: "+ Money, Toast.length_short). Show ();} /** * Method of selection for ListView item */@Overridepublic void Onitemclick (adapterview<?> parent, view view, int position, long ID {//Gets the Viewholder object, which eliminates the steps to instantiate the CB instance we need through layer Findviewbyid viewholder holder = (viewholder) view.gettag ();// Change the status of the CheckBox Holder.cb.toggle ();//Record the checkbox's selection Status mylistviewadapter.getisselected (). put (position, Holder.cb.isChecked ());}}
the principle of dynamic Control checkbox display can be easily understood by initializing the adapter incoming parameters, depending on the code.
Take a look at the dynamic graph effect:

Looks uglier, Haihan.

Favorite friends can follow me and my public number, thank you!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Real-time tutorial-51st Gun (ListView Dynamic Display and hide of child controls, checkbox Select All and reverse)

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.