C # How programmers learn the Android Development Series ListView
The previous blog solved the problem of Android client interaction with server programs through WebService. This blog focuses on two issues: how Android applications interact with SQLite, a local file database, another question is how to display the desired interface effect in ListView. This article focuses on ListView, And the next blog focuses on SQLite.
ListView is a common data display control. Suppose we want to make a simple interface ,.
This figure is taken directly from the Android tablet (Android 4.2.2) and is a normal list. You can click the register button to obtain the information of the corresponding row.
The data shown here is queried from the SQLite database. The encapsulated class code is as follows:
Public class MyDatabaseHelper extends SQLiteOpenHelper {private static final String name = "mydb. db "; // SQLite database file name private static final int version = 1; // SQLite database version number public MyDatabaseHelper (Context context) {super (context, name, null, version );} @ SuppressLint ("SimpleDateFormat") @ Overridepublic void onCreate (SQLiteDatabase db) {try {// enable transaction db. beginTransaction (); String SQL = "create table jobInfo (n Ame varchar (20), "+" num integer, "+" date varchar (10), "+" description text) "mongodb.exe cSQL (SQL ); // test the insertion of 10 data records for (int I = 0; I <10; I ++) mongodb.exe cSQL ("insert into jobInfo (name, num, date, description) values (?,?,?,?) ", New Object [] {" name "+ I, I, new SimpleDateFormat (" yyyy-MM-dd "). format (new Date (), "description" + I});} // identifies the successful db of the transaction. setTransactionSuccessful ();} finally {// end the transaction db. endTransaction () ;}@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// Database Upgrade operation }}You can instantiate the MyDatabaseHelper class where you need to create a database and insert data. For more information about SQLite, see the next blog.
Activity_main.xml layout file:
We can see that this is a relative layout with a linear layout. Four textviews are placed in the linear layout as the title of the ListView data. The following is a ListView control. As this is a relative layout, we set the layout_below attribute to display the ListView under the "Header. In addition, pay attention to the id of ListView.
Then, according to the interface requirements, we prepare the content of the ListView loading layout file, which is called list_item.xml.
List_item.xml:
This is also a general linear layout, with orientation set to horizontal (horizontal ).
The layout file is ready. Now we are ready to write code.
The MainActivity class is inherited from ListActivity. The complete code is as follows:
Public class MainActivity extends ListActivity {List
> List; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); list = new ArrayList
> (); // Initialize the SQLite database operation class Object MyDatabaseHelper dbHelper = new MyDatabaseHelper (MainActivity. this); // query the database and return the Cursor (Cursor) object cursor Cursor = dbHelper. getReadableDatabase (). query ("jobInfo", new String [] {"name", "num", "date", "description"}, null, "name"); // encapsulate the result set to List
> In the data structure, while (cursor. moveToNext () {Map
Map = new HashMap
(); 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);} // the query is complete. Close the database link cursor in time. 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. id. description, R. id. btn}); // set the data filling adapter ListView = (listView) findViewById (android. r. id. list); listView. setAdapter (adapter) ;}@ Overrideprotected void onListItemClick (ListView l, View v, int position, long id) {// @ SuppressWarnings ("unchecked") Map of ListView
Map = (HashMap
) L. getItemAtPosition (position); Toast. makeText (MainActivity. this, "you clicked:" + map. get ("name"). toString () +! ", 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
> MList; private ButtonViewHolder holder; private LayoutInflater mInflater; private String [] keyString; private int [] valueViewID; // The initialization variable of the constructor public MyButtonAdapter (Context context, List
> List, int resource, String [] from, int [] to) {this. mContext = context; this. mList = list; // obtain the layout file object mInflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE); keyString = new String [from. length]; valueViewID = new int [. length]; // copy the array System. arraycopy (from, 0, keyString, 0, from. length); System. arraycopy (to, 0, valueViewID, 0,. length) ;}@ Overridepublic int getCount () {r Eturn 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 that the dataset has changed and request auto-refresh this. notifyDataSetChanged () ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic View getView (int position, View convertView, ViewGroup parent) {if (convertView! = Null) {holder = (ButtonViewHolder) convertView. getTag ();} else {convertView = mInflater. inflate (R. layout. list_item, null); holder = new ButtonViewHolder (); holder. name = (TextView) convertView. findViewById (valueViewID [0]); // post name holder. num = (TextView) convertView. findViewById (valueViewID [1]); // number of positions holder. date = (TextView) convertView. findViewById (valueViewID [2]); // release date holder. description = (TextView) convertView. findViewById (valueViewID [3]); // post description holder. btn = (Button) convertView. findViewById (valueViewID [4]); // The register button convertView. setTag (holder);} Map
AppInfo = mList. get (position); if (appInfo! = Null) {String aname = (String) appInfo. get (keyString [0]); Integer anum = (Integer) appInfo. get (keyString [1]); String adate = (String) appInfo. get (keyString [2]); String adeworkflow = (String) appInfo. get (keyString [3]); holder. name. setText (aname); holder. num. setText (anum + ""); holder. date. setText (adate); holder. description. setText (adegion); // register 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 = "" + "job name:" + list. get (position ). get ("name") + "\ r \ n" + "number of positions:" + 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 ("prompt "). 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, applied for" + list. get (position ). get ("name") +! ", 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, "you clicked" + getResources (). getString (R. string. negative) + "button", Toast. LENGTH_SHORT); toast. setGravity (Gravity. CENTER, 0, 0); toast. show ();}}). create (). show (); // call this method if you want to delete a row. // removeItem (position );}}}}}
The above code has several knowledge points to note:
1. query the SQLite Database
We performed the query operation through the getReadableDatabase (). query method and returned the Cursor (Cursor, similar to the ResultSet in JDBC) object.
2. ListView control usage (important)
We refer to the SimpleAdapter default constructor method and create a custom MyButtonAdapter class. When displaying data, we can bind a click event to the buttons in each row.
3. A prompt box is displayed.
The code in the pop-up prompt box is very long and can be completely encapsulated into a method to simplify the code. The purpose of this complete list is to experience the design concept. After observation, we found that this is the so-called "chain programming". You can set parameters (control the display effect) through continuous ).
Strings. xml:
OK
Cancel
The execution result on the pad is as follows: