Android practice simple tutorial-51st gun (ListView achieves Dynamic Display and hiding of sub-controls, full selection of checkbox and reverse selection), androidlistview

Source: Internet
Author: User

Android practice simple tutorial-51st gun (ListView achieves Dynamic Display and hiding of sub-controls, full selection of checkbox and reverse selection), androidlistview

I wrote an article some time ago: Android practice simple tutorial-47th gun (ListView multiple choice-ordering system) Some people leave a message to suggest, can I dynamically control the display of the checkbox and the Select All function? I have studied it and found that it is easy to implement it. Close up this article. Learning is about divergent thinking. You can also modify, add, and delete some functions based on my instance. This will improve your knowledge! Let's take a look at the code below:

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: layout_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: 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" android: layout_width = "wrap_content" android: layout_height = "58dp" android: text = "select all"/> <Button android: id = "@ + id/btn_select_cancel" android: layout_width = "wrap_content" android: layout_height = "58dp" android: text = ""/> </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 = "wrap_content" android: layout_height = "wrap_content" android: clickable = "false" android: focusable = "false" android: focusableInTouchMode = "true"/> <ImageView android: id = "@ + id/food_imager" android: layout_width = "50dp" android: layout_height = "50dp" android: background = "# ffffff"/> <TextView android: 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 = "unit price: RMB" 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 = "18" android: layout_marginLeft = "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 String 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_name;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 fills in data; // It is used to control the CheckBox selection status private static HashMap <Integer, Boolean> isSelected; // Context private context Context; // used to import the layout 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) {// obtain the ViewHolder object holder = new ViewHolder (); // import the layout and assign it to convertviewconvertView = inflater. inflate (R. layout. item, null); holder. imageView = (ImageView) convertview.findviewbyid(r.id.food_imager%%holder.txt 1 = (TextView) convertview.findviewbyid(r.id.food_name%%%holder.txt 2 = (TextView) convertView. findViewById (R. id. price); holder. cb = (CheckBox) convertView. findViewById (R. id. check_box); // set the label convertView for the view. setTag (holder);} else {// retrieve holderholder = (ViewHolder) convertView. getTag ();} // get the data Food food = foodlist. get (position); // fill in the data to the corresponding control of the current convertView if (isShow) {holder. cb. setVisibility (View. VISIBLE);} else Release 2. setText (food. food_price); // set the display of TextView in the list // set the checkbox selection status based on 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; private Button OK, mSe LectButton, mSelectAllButton, mCancelAllButton; private ArrayList <Food> foods = new ArrayList <Food> (); private MyListViewAdapter adapter; private CheckBox checkBox; private int checkNum; // record the number of selected entries: private ArrayList <String> list; private Boolean isShow = false; private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {if (msg. what = 1) {adapter = new MyListViewAdapter (Foods, getApplicationContext (), 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 the control 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);}/*** initialization control */public void initView () {listView = (ListView) findViewById (R. id. drink_list); // listview list control OK = (Button) findViewById (R. id. btn_commit); // confirm the 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"); 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", "10"); foods. add (new Food (cls. getDeclaredField ("d2 "). getInt (null), "orange juice", "12"); foods. add (new Food (cls. getDeclaredField ("d3 "). getInt (null), "beer", "15"); foods. add (new Food (cls. getDeclaredF Ield ("d4 "). getInt (null), "grape juice", "10"); foods. add (new Food (cls. getDeclaredField ("d5 "). getInt (null), "Milk Tea", "8"); foods. add (new Food (cls. getDeclaredField ("d6 "). getInt (null), "mint juice", "10"); foods. add (new Food (cls. getDeclaredField ("d7 "). getInt (null), "Lemon Mint", "12"); 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", "10"); for (int I = 0; I <foods. size (); I ++) {list. add ("data" + "" + I) ;};} catch (Exception e) {e. printStackTrace () ;}/ *** Click Event Processing */@ Overridepublic void onClick (View v) {int mID = v. getId (); switch (mID) {case R. id. btn_commit: myPrice (); // calculates the total price and outputs the break; case R. id. btn_select: if (isShow) {Message message = Message. obta In (); message. what = 0; handler. sendMessage (message); mSelectButton. setText ("order");} 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 and set all map values in MyAdapter to truefor (int I = 0; I <list. size (); I ++) {MyListViewAdapter. getIsSelected (). put (I, true);} // The number is set to the length of the list checkNum = list. size (); // refresh listvi Display adapter of ew and TextView. yydatasetchanged (); break; case R. id. btn_select_cancel: // traverses the length of the list and sets all map values in MyAdapter to truefor (int I = 0; I <list. size (); I ++) {MyListViewAdapter. getIsSelected (). put (I, false);} // The number is set to the length of the list checkNum = list. size (); // refresh the display adapter of listview and TextView. notifyDataSetChanged (); break ;}/ *** method for calculating the total price */public void myPrice () {HashMap <Integer, Boolean> map = MyListViewAdapter. getIs Selected (); 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 (), "selected" + str + ", total price:" + money, Toast. LENGTH_SHORT ). show ();}/*** method for selecting items in listview */@ Overridepublic void onItemClick (AdapterView <?> Parent, View view, int position, long id) {// get the ViewHolder object, this eliminates the need to instantiate the cb instance step ViewHolder holder = (ViewHolder) view through the layer-by-layer findViewById. getTag (); // Changes the status of the CheckBox holder. cb. toggle (); // record the CheckBox selection status to MyListViewAdapter. getIsSelected (). put (position, holder. cb. isChecked ());}}
The principle of dynamic control of checkbox display is passed in parameters by initializing the Adapter. For details, you can refer to the code, which is easy to understand.
Take a look at the dynamic graph effect:

Looks ugly, Hai Han

If you like it, you can follow me and my public account. Thank you!

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.