C # Programmer learns the ListView of the Android Development series

Source: Internet
Author: User

The previous blog addresses the problem of Android clients interacting with server-side programs via WebService, a blog that focuses on two issues, one of how Android applications interact with the native file database SQLite. The other question is how to display the interface effects that we want in the ListView. Confined to this focus on the ListView, the next blog focuses on SQLite.

The ListView is a common data display control, assuming we want to do a simple interface.


This picture is I directly from the Android tablet (Android 4.2.2) down, is a normal list, can click the registration button to get the corresponding line information.

This shows the data that I queried from the SQLite database, the code of the encapsulated class is as follows:

public class Mydatabasehelper extends Sqliteopenhelper {private static final String name = "Mydb.db";//SQLite database file name private static FINA l int version = 1;//SQLite database version number public Mydatabasehelper (context context) {Super (context, name, null, version);} @SuppressLint ("SimpleDateFormat") @Overridepublic void OnCreate (Sqlitedatabase db) {try {//Open transaction db.begintransaction () ; String sql = "CREATE TABLE jobinfo (name varchar)," + "num Integer," + "date varchar (ten)," + "description text)";d B.execs QL (SQL);//test Insert 10 data for (int i = 0; i < i++) {Db.execsql ("INSERT into Jobinfo (name,num,date,description) VALUES (?,?, ?,?) ", new object[] {" name "+ i,i,new SimpleDateFormat (" Yyyy-mm-dd "). Format (new Date ())," description "+ i}); Identify transaction success db.settransactionsuccessful ();} finally {//End transaction db.endtransaction ();}} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//Database upgrade operation}} 
You can instantiate the Mydatabasehelper class when you need to create a database or insert data, and the next blog will explain more about the details of SQLite.

Activity_main.xml Layout file:

<relativelayout 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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" > < LinearLayout android:id= "@+id/head" android:layout_width= "match_parent" android:layout_height= "Wrap_c            Ontent "android:orientation=" horizontal "> <textview android:layout_width=" wrap_content "            android:layout_height= "wrap_content" android:text= "Job name" android:textsize= "24SP" Android:width= "150dip"/> <textview android:layout_width= "Wrap_content" android:layout      _height= "Wrap_content" android:text= "Number of posts"      Android:textsize= "24SP" android:width= "150dip"/> <textview android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "Release date" android:textsize=            "24sp" android:width= "150dip"/> <textview android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Job description" android:textsize= "24SP" Andro Id:width= "550dip"/> </LinearLayout> <listview android:id= "@id/android:list" android:layou T_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/head" > </Li Stview></relativelayout>
You can see that this is a relative layout, with a linear layout inside, and a linear layout with 4 TextView as the header for the ListView data. Here is a ListView control, because this is a relative layout, in order for the ListView to appear under "Table Header", we set the Layout_below property. Also note the notation of the ListView ID.

Then according to the requirements of the interface, we prepared the ListView loading layout file content, we named: List_item.xml.

List_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:orientation=" Horizontal "> <textview android:id=" @+id/name "android:layout_width=" Wrap_content "Android:layout_heig ht= "Wrap_content" android:textsize= "24sp" android:width= "150dip"/> <textview android:id= "@+ Id/num "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:textsize=" 24 SP "android:width=" 150dip "/> <textview android:id=" @+id/date "android:layout_width=" Wrap_co Ntent "android:layout_height=" wrap_content "android:textsize=" 24sp "android:width=" 150dip "/> & Lt TextView android:id= "@+id/description" android:layout_width= "wrap_content" android:layout_height= "Wra P_content "Android:textsiZe= "24SP" android:width= "550dip"/> <button android:id= "@+id/btn" android:layout_width= "wrap _content "android:layout_height=" Wrap_content "android:focusable=" false "Android:focusableintouchmode = "false" android:text= "registration" android:width= "150dip" android:textsize= "24SP"/></linearlayout>
This is also an ordinary linear layout, set orientation to horizontal (horizontal).

The layout file is ready, so we're ready to write the code.

We let mainactivity this class inherit from Listactivity, the complete code is as follows:

public class Mainactivity extends Listactivity {list<map<string, object>> List; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); List = new arraylist<map<string, object>> ();//Initialize SQLite database Operation class object Mydatabasehelper DBHelper = new Mydatabasehelper (mainactivity.this);//Query database returns the cursor (cursor) object cursor cursor = dbhelper.getreadabledatabase (). Query (" Jobinfo ", new string[] {" name "," num "," date "," description "}, null,null, NULL, NULL," name ");//encapsulate the result set to List<map<st Ring,object>> data structure in while (Cursor.movetonext ()) {map<string, object> Map = new hashmap<string, Object > (); Map.put ("Name", cursor.getstring (0)), map.put ("num", Cursor.getint (1)), Map.put ("date", Cursor.getstring (2)) ; Map.put ("description", Cursor.getstring (3)), Map.put ("btn", R.drawable.ic_launcher); List.add (map);} Query finished, remember to close the database link cursor.close (); Mybuttonadapter adapter = new Mybuttonadapter (Mainactivity.this, List,r.layOut.list_item, new string[] {"name", "num", "date", "description", "BTN"}, new int[] {r.id.name,r.id.num, r.id.date, R.I D.description, r.id.btn});//Set Data fill Adapter for ListView ListView ListView = (ListView) Findviewbyid (Android. r.id.list); Listview.setadapter (adapter);} @Overrideprotected void Onlistitemclick (ListView l, View v, int position, long id) {//listview @suppresswarnings (" Unchecked ") map<string, object> Map = (hashmap<string, object>) l.getitematposition (position); Toast.maketext (Mainactivity.this, "you clicked:" + map.get ("name"). ToString () + "Post!" ", Toast.length_short). Show ();} public class Mybuttonadapter extends Baseadapter {private class Buttonviewholder {TextView name; TextView num; TextView date; TextView description; Button btn;} Private Context mcontext;private list<map<string, object>> mlist;private buttonviewholder holder;private Layoutinflater minflater;private string[] keystring;private int[] valueviewid;//constructor initializes the variable public mybuttonadapter ( Context Context, List<map<string, object>> list,int Resource, string[] from, int[] to) {This.mcontext = Context;this.mlist = list;//Get layout File Object minflater = (layoutinflater) context.getsystemservice (context.layout_inflater_service); keyString = new String[ From.length];valueviewid = new int[to.length];//copy array system.arraycopy (from, 0, keystring, 0, from.length); System.arraycopy (To, 0, Valueviewid, 0, to.length);} @Overridepublic int GetCount () {return list.size ();} @Overridepublic Object getItem (int position) {return list.get (position);} /** * Remove an item from the list * * @param position */public void RemoveItem (int position) {list.remove (position);//notification data set changed, request self-refresh this . notifydatasetchanged ();} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {if (Convertview! = null) {holder = (Button Viewholder) Convertview.gettag ();} else {Convertview = minflater.inflate (R.layout.list_item, null); holder = new Buttonviewholder (); holder.name = (TexTView) Convertview.findviewbyid (valueviewid[0]);//Job name Holder.num = (TextView) Convertview.findviewbyid (valueviewid [1]); /number of posts Holder.date = (TextView) Convertview.findviewbyid (valueviewid[2]);//Release date holder.description = (TextView) Convertview.findviewbyid (valueviewid[3]);//Job Description holder.btn = (Button) Convertview.findviewbyid (valueviewid[4]);// Registration button Convertview.settag (holder);} map<string, object> appInfo = mlist.get (position); if (appInfo! = null) {String aname = (string) appinfo.get (Keystrin G[0]); Integer anum = (integer) appinfo.get (keystring[1]); String adate = (string) appinfo.get (keystring[2]); String adescription = (string) appinfo.get (keystring[3]); Holder.name.setText (aname); Holder.num.setText (Anum + ""); Holder.date.setText (adate); Holder.description.setText (adescription);//Registration button Event Holder.btn.setOnClickListener (new Lvbuttonlistener (position));} return Convertview;} Class Lvbuttonlistener implements Onclicklistener {private int position;lvbuttonlistener (int pos) {position = pos;} @Overridepublic void OnClick (View v) {int vid = V.getid (); if (vid = = Holder.btn.getId ()) {String result = "+" Post name: "+ LIST.G ET (position). Get ("name") + "\ r \ n" + "Post Number:" + list.get (position). Get ("num") + "\ r \ n" + "Release date:" + list.get (position). Get (" Date ") +" \ r \ n "+" Job Description: "+ list.get (position). Get (" description ") +" \ r \ n "; new Alertdialog.builder (Mainactivity.this). Settitle ("hint"). SetIcon (R.drawable.ic_launcher). Setmessage (Result + "\ r \ n" + "Are you sure you want to apply for this position?" "). Setpositivebutton (R.string.positive,new Dialoginterface.onclicklistener () {@Overridepublic void OnClick ( Dialoginterface Dialog,int which) {Toast toast = Toast.maketext (Mainactivity.this, "you clicked" + getresources (). GetString ( r.string.positive) + "button, request" + list.get (position). Get ("name") + "Post!" ", Toast.length_short); Toast.setgravity (Gravity.center, 0,0); Toast.show ();}}). Setnegativebutton (r.string.negative,new Dialoginterface.onclicklistener () {@Overridepublic void OnClick ( Dialoginterface Dialog,int which) {Toast toast = Toast.maketext (Mainactivity.this, "youClicked "+ getresources (). getString (r.string.negative) +" button ", Toast.length_short); Toast.setgravity (Gravity.center, 0,0) ; Toast.show ();}}). Create (). Show ();//If you want to delete a row, you can call this method//RemoveItem (position);}}}}

The above code has several knowledge points to note:

1, the query operation of SQLite database

We performed a query operation through the Getreadabledatabase (). Query method, which returns the cursor (cursor, similar to resultset in JDBC) object.

2. Using the ListView Control (emphasis)

We refer to the method of Simpleadapter default constructors, and create custom mybuttonadapter classes that, while displaying data, can bind a point-and-click event to a button for each row.

3. Pop-up Prompt box

The code for the popup box is very long and can be encapsulated in a method, simplifying the code. Here is the complete list, the purpose is to experience the design ideas. After observation we found that this is called "chain programming", you can set the parameters (control the display effect) through continuous "."

Strings.xml:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <string    name= "positive" > OK </string>    <string name= "negative" > Cancel </string></resources>

Finally, the performance on the pad is as follows:









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.