Sort out the ListView in Android

Source: Internet
Author: User

In Android, listview is a frequently used component. So let's summarize the basic usage of listview today.


I. Basic binding

Java code:

Package com. tmnw; import java. util. arrayList; import java. util. list; import android. app. activity; import android. OS. bundle; import android. widget. arrayAdapter; import android. widget. listView; public class MainActivity extends Activity {/* ---- ListView MVC implementation ---- * // model List <String> data; // view ListView lv; // controller ArrayAdapter <String> adapter; int size = 1; // initialize the private void initWidget () {lv = (ListView) findViewById (R. id. list);} // initialize the bound data private void initData () {if (lv = null) return; // Step 1: obtain the data source model) data = new ArrayList <String> (); appendData (); // Step 2: new adapter controller) // parameter 1: Context // parameter 2: listview's item layout // parameter 3: id of the control whose data is filled in the item layout // parameter 4: filled data adapter = new ArrayAdapter <String> (this, R. layout. simple_text, R. id. text1, data); // Step 3: Set the adapter view for listview) lv. setAdapter (adapter);} // Add data private void appendData () {if (data = null) return; for (int I = 0; I <10; I ++) {data. add ("" + size ++) ;}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initWidget (); initData ();}}

Sputation for the magic horse removed the blank line in my code, it feels ugly 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105424524-0.gif "/>)

Xml code:

Activity_main.xml

<LinearLayout 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:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <ListView        android:id="@+id/list"        android:layout_width="match_parent"        android:layout_height="0dip"        android:layout_weight="1" >    </ListView></LinearLayout>

Simple_text.xml

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/text1"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:padding="5dp"    android:textIsSelectable="false" />

Image effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105424Y0-1.png "title =" arrayadapter.png "/>


2. Add headers and tails to ListView

Java code:

// Initialize the private void initWidget () {lv = (ListView) findViewById (R. id. list); header = getLayoutInflater (). inflate (R. layout. simple_text, null); (TextView) header. findViewById (R. id. text1 )). setText ("this is a header"); footer = getLayoutInflater (). inflate (R. layout. simple_text, null); (TextView) footer. findViewById (R. id. text1 )). setText ("loading... ");} // initialize the bound data private void initData () {if (lv = null) return; // Step 1: obtain the data source model) data = new ArrayList <String> (); appendData (); // Step 2: new adapter controller) // parameter 1: Context // parameter 2: listview's item layout // parameter 3: id of the control whose data is filled in the item layout // parameter 4: filled data adapter = new ArrayAdapter <String> (this, R. layout. simple_text, R. id. text1, data); // Step 3: Set an adapter view for listview) // make sure that either addHeaderView or addFooterView is called before setAdapter, or both call lv before setAdapter. addHeaderView (header); lv. setAdapter (adapter); // The null parameter indicates data, and false indicates that lv cannot be selected. addFooterView (footer, null, false); // you can specify no split line at the end. The same line is left when you do not want to split the line at the head. setFooterDividersEnabled (false );}

Only partially modified code 650 is pasted) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105424O2-2.gif "/>)

Image effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105425N3-3.png "title =" lv2.png "/>

3. Add a method for downloading ListView

Because listview needs to be rolled, you can add a rolling listener to it. For ease of writing, I have enabled OnScrollListener for this Activity.

public class MainActivity extends Activity implements OnScrollListener

Java code:

Add several variables first

Button scrollInfo;Thread currentThread;

Modify the initialization component code

Lv = (ListView) findViewById (R. id. list); scrollInfo = (Button) findViewById (R. id. scroll_info); header = getLayoutInflater (). inflate (R. layout. simple_text, null); (TextView) header. findViewById (R. id. text1 )). setText ("this is a header"); footer = getLayoutInflater (). inflate (R. layout. simple_text, null); (TextView) footer. findViewById (R. id. text1 )). setText ("loading... ");


Add in onCreate

lv.setOnScrollListener(this);

OnScrollListenerMethod:

@ Overridepublic void onScrollStateChanged (AbsListView view, int scrollState) {switch (scrollState) {// slide case OnScrollListener when your fingers reach the screen. SCROLL_STATE_TOUCH_SCROLL: // inertial sliding case OnScrollListener when the finger leaves the screen. SCROLL_STATE_FLING: // load the data if (view. getLastVisiblePosition () = view. getCount ()-1) {// you can load data through the network. // Determine whether it is still loading. if (currentThread = null |! CurrentThread. isAlive () {// Add the left-side navigation bar (lv) to be loaded in the listview tail control. addFooterView (footer, null, false); // start the thread to load data currentThread = new DataLoadThread (); currentThread. start () ;}} break; // do not slide case OnScrollListener. expiration: break ;}@ Overridepublic void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {// firstVisibleItem: the position of the first displayed item // visibleItemCount: number of items currently displayed // totalItemCount: Total number of items in listview scrollInfo. setText ("first:" + firstVisibleItem + "visible:" + visibleItemCount + "total:" + totalItemCount );}

Add a data loading thread

// Simulate loading data class DataLoadThread extends Thread {@ Override public void run () {try {Thread. sleep (2000); appendData (); // because the Android control can only be updated through the main thread ui thread), this method is used to runOnUiThread (new Runnable () {@ Override public void run () {// after loading, remove the end control lv. removeFooterView (footer); // call this method to notify the view to update the adapter when the data changes. notifyDataSetChanged () ;}});} catch (InterruptedException e) {e. printStackTrace ();}}}

Image effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105425335-4.png "title =" lv3.png "/>

4. Add an item click event to ListView

For ease of writing, I made this Activity implement OnItemClickListener

public class MainActivity extends Activity implements OnScrollListener,        OnItemClickListener

Java code:

Then implement the Method

@Override    public void onItemClick(AdapterView<?> parent, View view, int position,            long id) {        Toast.makeText(                this,                "position:" + position + "  item:"                        + parent.getItemAtPosition(position).toString(),                Toast.LENGTH_LONG).show();    }

Add listeners to listview

lv.setOnItemClickListener(this);


Image effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105423317-5.png "title =" lv4.png "/>

(Simulator problems using the real machine debugging, did not expect the picture so big, but faster than the simulator 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/110542HI-6.gif "/>)


V. Use of custom adapters

Java code:

// Customize the basic adapter class MyAdapter extends BaseAdapter {// The number displayed by listview. If there are 10 data sources, 5 is returned, then lv will always display only five results // It is better to return the number of data sources. @ Override public int getCount () {return data. size () ;}// call @ Override public Object getItem (int position) {return data when getting the data bound to the item. get (position) ;}// itemId @ Override public long getItemId (int position) {return position ;}// lv displays several items and calls this method several times, then return a view object display // position: Location // convertView: If the lv cannot display all the data, after scrolling, the View from the display to the display will be passed in and reused @ Override public View getView (int position, View convertView, ViewGroup parent) {View view; if (convertView = null) {view = getLayoutInflater (). inflate (R. layout. simple_text, null);} else {view = convertView;} TextView TV = (TextView) view. findViewById (R. id. text1); TV. setText (data. get (position); // the color of the line. if (position & 1) = 1) {TV. setBackgroundResource (android. r. color. holo_green_light);} else {TV. setBackgroundResource (android. r. color. holo_red_light) ;}return view ;}}


Modify setAdapter ()

// adapter = new ArrayAdapter<String>(this, R.layout.simple_text,        // R.id.text1, data);        adapter = new MyAdapter();


Image effect:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/110542K11-7.png "title =" lv5.png "/>


Source code

(Base until now, it's another chicken-flavored weekend 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1105425158-8.gif "/>)

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.