Learn android from scratch (ListView data list display component. 21 .)

Source: Internet
Author: User

Learn android from scratch (ListView data list display component. 21 .)
Similar to ScrollView, there is also a list component (ListView) that can add multiple components to the ListView to achieve the scrolling display effect of the component, the ListView component itself also supports the corresponding ListView class. You can operate the ListView class to complete operations on this group of components. The Inheritance structure of the ListView class is as follows: java. lang. object? Android. view. View? Android. view. ViewGroup? Android. widget. AdapterView ? Android. widget. AbsListView? Android. widget. ListView

Public ListView (Context context) Structure Create an instantiated object of the ListView class
Public void setAdapter (ListAdapter adapter) Normal Set the displayed data
Public ListAdapter getAdapter () Normal Returns the ListAdapter
Public void setOnItemSelectedListener (AdapterView. OnItemSelectedListener listener) Normal This event is triggered when the option is selected.
To display ListView data, you must use an Adapter data container to store and manage data.
Known Indirect Subclasses (a Known subclass) ArrayAdapter , BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, and WrapperListAdapter , BaseAdapter and simpleAdapter today we will learn how to use these adapters and listView

First, let's take a look at ArrayAdapter. He supports the centralized construction method ArrayAdapter. (Context, textViewResourceId) input a context object, display mode
ArrayAdapter (Context, resource, textViewResourceId) input a context object, resource ID, display mode ArrayAdapter (Context, textViewResourceId, objects) to pass in a context object, display format, and display data (can be an array of objects or an object set)
ArrayAdapter (Context, resource, textViewResourceId, objects) input a context object, resource ID, display format, and display data (can be an array of objects or an object set)


Below we will use the column sub-classes we have previously done to briefly explain the XMl file
          
       
      

JAVA files
Package com. example. listview; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. arrayAdapter; import android. widget. listView; import android. widget. toast; public class MainActivity extends Activity {private ListView listView; private final String data [] = {"nickname: wind, snow, not yang", "Gender: male", "age: 22 years old "," School: Henan University "," Department: School of Educational Science "," Mailbox: fangjaylong@gmail.com "}; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); listView = (ListView) this. findViewById (R. id. listview); listView. setAdapter (new ArrayAdapter
      
       
(MainActivity. this, android. R. layout. simple_list_item_1, data); listView. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
       Parents, View view, int position, long id) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, "you have selected" + data [position], Toast. LENGTH_SHORT ). show ();}});}}
      

Display Effect





The following describes how to use SimpleAdapter.
Use simpleAdapter to implement the LIstVIew effect with titles
The constructor is as follows:
SimpleAdapter (Context context, List > Data, int resource, String [] from, int [])

The basic usage will give you a detailed comment on the configuration of the Xml file in the code.
          
           
       
      

JAVA files
Package com. example. listview2; import java. util. arrayList; import java. util. hashMap; import java. util. map; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. listView; import android. widget. simpleAdapter; import android. widget. toast; public class MainActivity extends Activity {private final String Title [] = {"nickname:", "Gender:", "Age:", "School:", "department: "," Email: "}; // Title data private final String contents [] = {" Feng feixue weiyang "," male "," 22 ", "Henan University", "school of Educational Science", // content data "fangjaylong@gmail.com"}; private ListView listView = null; ArrayList
      
       
> List = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); listView = (ListView) this. findViewById (R. id. listview); list = new ArrayList
       
        
> (); // Instantiate listfor (int I = 0; I <Title. length; I ++) {// for loop to add data Map to the list
        
         
Map = new HashMap
         
          
(); // Create a map object map. put ("title", Title [I]); map. put ("content", contents [I]); list. add (map); // add map data to list} // set adapterlistView for ListView. setAdapter (new SimpleAdapter (MainActivity. this, // context Object list, // List data android. r. layout. simple_list_item_2, // Display Method of Data in ListView new String [] {"title", "content "}, // The String data here must correspond to the key value in the List. new int [] {android. r. id. text1, android. r. id. text2}); // android. r. layout. text control provided in simple_list_item_2 // android. r. id. text1, android. r. id. text2 attributes are created by // android. r. layout. simple_list_item_2 is provided by the system layout. You can try other controls in it. // Click Event listView to set the data items in listView. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
          Parent, View view, int psition, long id) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, "you selected" + Title [psition] + contents [psition], Toast. LENGTH_SHORT ). show (); // toast prompt }});}}
         
        
       
      
:

The above uses the display effects provided by android. You can also customize the appropriate display effects based on your needs. Below we use the custom Layout to achieve the effect of text-and-text mixing.

Xml file
          
           
       
      

Custom xml file
      
          
           
           
       
      


JAVA file configuration
Package com. example. lsitview3; import java. util. arrayList; import java. util. hashMap; import java. util. map; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. listView; import android. widget. simpleAdapter; import android. widget. toast; public class MainActivity extends Activity {private final String Title [] = {"nickname:", "Gender:", "Age:", "School:", "department: "," Email: "}; // Title data private final String contents [] = {" Feng feixue weiyang "," male "," 22 ", "Henan University", "school of Educational Science", // content data "fangjaylong@gmail.com"}; private ListView = null; private int image [] = {R. drawable. a1, R. drawable. a2, R. drawable. a3, R. drawable. a4, R. drawable. a5, R. drawable. a6}; // set the image data ArrayList
      
       
> List = null; // set the second parameter to Object to facilitate receiving other types of parameters @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); listView = (ListView) this. findViewById (R. id. listView1); list = new ArrayList
       
        
> (); // Instantiate listfor (int I = 0; I <Title. length; I ++) {// for loop to add data Map to the list
        
         
Map = new HashMap
         
          
(); // Create a map object map. put ("image", image [I]); map. put ("title", Title [I]); map. put ("content", contents [I]); list. add (map); // add map data to list} // set adapterlistView for ListView. setAdapter (new SimpleAdapter (MainActivity. this, // context Object list, // List data R. layout. custom, // Display Method of Data in ListView new String [] {"image", "title", "content "}, // The String data here must correspond to the key value in the List. new int [] {R. id. imageView1, R. id. textView1, R. id. textView2}); // Control id of the custom Layout // Click Event listView for the data item settings in listView. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
          Parent, View view, int psition, long id) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, "you selected" + Title [psition] + contents [psition], Toast. LENGTH_SHORT ). show (); // toast prompt }});}}
         
        
       
      

Final Effect



Use of BaseAdapter
Known Direct Subclasses (a Known subclass)
ArrayAdapter , CursZ success? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys/keys + keys/J0tTH4cvJyrXP1rbUyv2 + 3bXEz9TKvrLZ1/e6zbbUyv2 + 3 cbky/keys + keys =" http://www.2cto.com/uploadfile/Collfiles/20140817/2014081709342167.png "alt = "\">

Xml file configuration
           
            
        
       

Custom xml
       
           
            
            
        
       

JAVA file configuration
Package com. example. listview; import android. app. activity; import android. content. context; import android. graphics. color; import android. OS. bundle; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. baseAdapter; import android. widget. imageView; import android. widget. listView; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {private ListView listView; private Myadapter adapter; private final String titles [] = {"nickname:", "Gender:", "Age :", "School:", "Don't:", "Email:"}; // Title data private final String contents [] = {"Feng feixue weiyang", "male ", "22 years old", "Henan University", "school of Educational Science", "fangjaylong@gmail.com"}; // content data private int images [] = {R. drawable. a1, R. drawable. a2, R. drawable. a3, R. drawable. a4, R. drawable. a5, R. drawable. a6}; // image data @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) this. findViewById (R. id. listView1); adapter = new Myadapter (this); listView. setAdapter (adapter); // sets the option of the listener event listView. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
       Arg0, View view, int position, long id) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, "you have selected:" + titles [position] + contents [position], Toast. LENGTH_LONG ). show (); // toast prompt});} class Myadapter extends BaseAdapter {// defines the color. Here two display types are defined alternately, you can define any color private int Color [] = {color. CYAN, Color. GREEN}; private Context myContext; // The constructor transmits the Context object. You can also use getApplicationContext () to obtain public Myadapter (Context myContext) {this. myContext = myContext;} @ Overridepublic int getCount () {// TODO Auto-generated method stubreturn titles. length; // number of returned list options} @ Overridepublic Object getItem (int position) {// TODO Auto-generated method stubreturn position; // returns the current position} @ Overridepublic long getItemId (int position) {// TODO Auto-generated method stubreturn position; // returns the selected ID} @ Overridepublic View getView (int position, view convertView, ViewGroup parent) {// obtain the color array id 0 or 1int colorId = position % color. length; // By caching convertView, you can use the cached contentView method to determine that a View is created if there is no View in the cache. If there is already a View in the cache, you can use the View in the cache, improved performance if (convertView = null) {// obtain the View object convertView = LayoutInflater. from (myContext ). inflate (R. layout. my_adapter_view, null);} // obtain the component ImageView image = (ImageView) convertView. findViewById (R. id. imageView1); TextView title = (TextView) convertView. findViewById (R. id. textView1); TextView content = (TextView) convertView. findViewById (R. id. textView2); // sets the component information image. setImageResource (images [position]); title. setText (titles [position]); content. setText (contents [position]); convertView. setBackgroundColor (color [colorId]); // return the mounted viewreturn convertView ;}}}

Final Effect


In this way, the listView and adapter are basically finished, and so much will be used in development. I hope that the readers can have a good grasp of all the above Code with comments, if you do not understand, you can leave a message below. I will reply immediately.
Next prediction: SeekBar drag bar

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.