Android learning notes (9) -- ListView introduction, androidlistview

Source: Internet
Author: User

Android learning notes (9) -- ListView introduction, androidlistview

As the most commonly used control on Android, ListView must be well mastered. Here we will introduce some basic knowledge and features of ListView and provide a simple example.

First, let's define layout:

?
123456789101112131415 <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/ll_root"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.listview.MainActivity">     <ListView        android:id="@+id/lv"        android:layout_width="match_parent"        android:layout_height="match_parent">    </ListView> </LinearLayout>

The interface is very simple, just adding a ListView control to a linear layout. Next we will discuss the problem of data display. Here we will talk about the Adapter (data Adapter) in Android. An Adapter can be seen as the data source of ListView, the data to be presented by ListView is transmitted to ListView in the form of an Adapter.

The specific knowledge about the Adapter will be discussed separately in later articles.

It should be noted that the design of ListView is also based on the MVC mode, namely:

M model data model (data entry type to be displayed)

V View: Listview

C Controller is the Adapter

Let's take a look at how the specific code is implemented: first, the onCreate method:

?
123456789 protectedvoid onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        lv = (ListView) findViewById(R.id.lv);        for(inti=0;i<50;i++){            strList.add("I am an entry"+i);        }              lv.setAdapter(newMyAdapter());    }

To display entries in Listview, you only need to call the lv. setAdapter method, but the MyAdapter class here needs to be written by ourselves. Here we can implement it through the inherited method. Here we will introduce the basic BaseAdapter. Other adapters will be introduced later:

// Default implementation class, generally starting with: Base Simple default
Private class MyAdapter extends BaseAdapter {

Private static final String TAG = "MyAdapter ";
/**
* Controls the total number of entries in the ListView.
*/
@ Override
Public int getCount (){
Return strList. size ();
}

@ Override
Public Object getItem (int position ){
Return null;
}

@ Override
Public long getItemId (int position ){
Return 0;
}

@ Override
Public View getView (int position, View convertView, ViewGroup parent ){
Log. I (TAG, "Return view object, location" + position );
TextView TV = new TextView (getApplicationContext ());
TV. setTextSize (20 );
// Obtain str information at the corresponding position
String str = strList. get (position );
TV. setText (str );
Return TV;
}

}

To implement a simple display function, you only need to complete two methods. One is getView, which returns the view to be displayed, and the other is getCount, which returns the total number of entries.

In addition, when executing a program, the ListView automatically determines the number of view objects to be generated based on the display length, that is, view objects that are not within the screen range will not be generated and will not be generated until they are about to scroll. In addition, if an existing object is rolled away, it will be processed by the Java garbage collector.

The advantage is that if the entire program has many entries, the system will not generate all view objects at a time, which can improve program performance and prevent memory overflow.

Complete code:

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 packagecom.example.listview; importjava.util.ArrayList;importjava.util.List; importandroid.app.Activity;importandroid.database.DataSetObserver;importandroid.nfc.Tag;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.Adapter;importandroid.widget.BaseAdapter;importandroid.widget.ListAdapter;importandroid.widget.ListView;importandroid.widget.TextView; publicclass MainActivity extends Activity {     privatestatic final String TAG = "MainActivity";    privateListView lv;    privateList<String> strList = newArrayList<String>();     @Override    protectedvoid onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        lv = (ListView) findViewById(R.id.lv);        for(inti=0;i<50;i++){            strList.add("I am an entry"+i);        }              lv.setAdapter(newMyAdapter());    }         // Default implementation class, generally starting with: Base Simple default    privateclass MyAdapter extends BaseAdapter{                 privatestatic final String TAG = "MyAdapter";        /**         * Controls the total number of entries in the ListView.         */        @Override        publicint getCount() {            returnstrList.size();         }         @Override        publicObject getItem(intposition) {            returnnull;        }         @Override        publiclong getItemId(int position) {            return0;        }         @Override        publicView getView(intposition, View convertView, ViewGroup parent) {            Log.i(TAG,"Returned view object, location"+position);            TextView tv =new TextView(getApplicationContext());            tv.setTextSize(20);                         tv.setTextColor(Color.BLACK);                        // Obtain str information at the corresponding position            String str = strList.get(position);            tv.setText(str);            returntv;        }             } }

Effect:

You are welcome to reprint it. Please indicate the source.


Moved from my blog, xge technical blog:

Http://www.xgezhang.com/android_listview_intro.html

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.