Android Combat Simple Tutorial-the 47th Gun (ListView multiple selection-to achieve a point meal system)

Source: Internet
Author: User

Usually in the out-of-the-box menu will often use the multi-select ListView, you can improve after adding their own projects. Here's a look at the code:

One, the code

1.main.xml: (consisting of a ListView and a button)

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= " Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <listview        android:id= "@+id/drink_list" android:layout_width= "Fill_        Parent "        android:layout_height=" 0DP "        android:layout_weight=" 1 ">    </ListView>    < Button        android:id= "@+id/btn_commit"        android:layout_width= "match_parent"        android:layout_height= " 58DP "        android:text=" OK "/></linearlayout>

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "    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> (Bean Class)

Package;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 ();}}

Package Com.example.adapter;import Java.util.arraylist;import Java.util.hashmap;import; 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;//Contexts Private context context;//is used to import layouts private Layoutinflater Inflater = null;//constructor Public Mylistviewadapter ( Arraylist<food> list, Context context) {This.context = Context;this.foodlist = List;inflater = Layoutinflater.from (context); isSelected = new Hashmap<integer, boolean> ();//Initialize Data initdate ();} Initializes the 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 (; holder.txt1 = (TextView) Convertview.findviewbyid (; holder.txt2 = (TextView) Convertview.findviewbyid (; HOLDER.CB = (CheckBox) Convertview.findviewbyid (;//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 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;} }

Package Com.example.listviewselectitem;import Java.util.arraylist;import Java.util.hashmap;import Com.example.adapter.mylistviewadapter;import Com.example.adapter.mylistviewadapter.viewholder;import;import Android.os.bundle;import;import Android.content.Context;import Android.view.layoutinflater;import Android.view.view;import Android.view.window;import Android.view.view.onclicklistener;import Android.widget.adapterview;import Android.widget.button;import Android.widget.checkbox;import Android.widget.listview;import Android.widget.toast;import Android.widget.adapterview.onitemclicklistener;public class Mainactivity extends Activity implements Onclicklistener , Onitemclicklistener {private ListView listview;private Button ok;private arraylist<food> foods = new ArrayList <Food> ();p rivate mylistviewadapter adapter;private CheckBox checkbox;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 (; InitData ();//Initialize virtual data adapter = new Mylistviewadapter (foods, Getapplicationcontext ()); Listview.setadapter (adapter);} /** * Initialize control * */public void Initview () {listview = (ListView) Findviewbyid (;//ListView List Control OK = (Button) F Indviewbyid (;//OK button 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 ("D 1 "). GETINT (null)," Kiwi Juice "," ten "), Foods.add (new Food (Cls.getdeclaredfield (" D2 "). GetInt (null)," Orange Juice "," n "); Foods.add (New food ("Cls.getdeclaredfield") getInt (null), "Beer", "D3"), 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");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", "ten"); Foods.add ( New Food (Cls.getdeclaredfield ("D9"). GetInt (null), "Pearl milk Tea", "9")), Foods.add (new Food (Cls.getdeclaredfield ("D10"). GetInt (NULL), "Pomegranate Juice", "10")); catch (Exception e) {e.printstacktrace ();}} /** * * * button's Click event handling * */@Overridepublic void OnClick (View v) {int mID = V.getid (); switch (MID) {case () ;//Calculate Total price and output break;}} /** * Method of calculating 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 ();} /** * How to select the item of the listview * */@Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {//Get Viewholder object, This eliminates the steps to instantiate the CB instance we need through layers of 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 ());}}
Second, the running example

favorite Friends Follow me and my public number (left column)! ThanksSource Download

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

Android Combat Simple Tutorial-the 47th Gun (ListView multiple selection-to achieve a point meal system)

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: 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.