Add more buttons at the bottom of the Android Demo tour ListView to implement data Paging

Source: Internet
Author: User

Add more buttons at the bottom of the Android Demo tour ListView to implement data Paging

In our actual project, there should be a lot of data, and our ListView cannot load all the data at once. We can scroll to the bottom of the ListView, for more tips, when we click it to load the data on the next page, it is equivalent to our paging effect. For more information, refer to the online content and write a small demo, some knowledge points are summarized as follows:


Source code: http://download.csdn.net/detail/harderxin/7762625

Knowledge points:

1) custom Adapter, bind data to ListView <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel/kernel vcD4KPHA + z + rPuLXEtPrC67TzvNK/kernel/C1NijrM/Cw + a4 + kernel/kernel + CjxwcmUgY2xhc3M9 "brush: java; "> public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); handler = new Handler (); // inherits the ListActivity, so you can use this method to retrieve listView = getListView (); initData (); // Add the bottom button View bottomView = getLayoutInflater (). inflate (R. layout. bottom, null); loadMore = (Button) bottomView. findViewById (R. id. load); loadMore. setOnClickListener (new ButtonClickListener (); listView. addFooterView (bottomView); // setListAdapter (adapter); listView. setAdapter (adapter); // set the event listView for listView. setOnItemClickListener (new OnItemListener (); listView. setOnScrollListener (new OnScrollListener ());}
The buttons at the bottom can be loaded through listView. addFooterView (View view); to define our button layout file:

 
    
  
 
Then we can use View bottomView = getLayoutInflater (). inflate (R. layout. bottom, null); obtain the View object, and then obtain our Button through the findViewById of the View object: loadMore = (Button) bottomView. findViewById (R. id. load );

2) initialize data. In this example, we initialize 10 data records and instantiate our custom adapter MyAdapter.

    public void initData(){    List
 
   datas=new ArrayList
  
   ();        for(int i=0;i<10;i++){        datas.add(i+1);        }        adapter=new MyAdapter(datas, this);    }
  
 

3) custom adapter MyAdapter: When the ListView interface is initialized or rolled, The getCount, getView, and other methods in it will be called and executed from time to time. Each time a row of ListView is drawn, getView is called once, and corresponding components are obtained and added;

Package com. xin. activity; import java. util. list; import android. content. context; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. imageView; import android. widget. textView; public class MyAdapter extends BaseAdapter {private List
 
  
Datas; private LayoutInflater flater; // constructor public MyAdapter (List
  
   
Datas, Context context) {this. datas = datas; flater = LayoutInflater. from (context);} // obtain the total number of data @ Overridepublic int getCount () {System. out. println ("aaa"); return datas. size () ;}// obtain each data entry @ Overridepublic Object getItem (int position) {return datas. get (position);} // obtain the position of the Project @ Overridepublic long getItemId (int position) {return position ;} /*** the items displayed in ListView get a View object by calling the getView method of the Adapter object * and put this View object in this item This process is the relationship between ListView and Adapter */@ Overridepublic View getView (int position, View convertView, ViewGroup parent) {ViewHolder viewHolder; if (convertView = null) {// generate a LayoutInflater object // inflater = LayoutInflater. from (context); // call the inflate method of the LayoutInflater object to generate a view object // LayoutInflater filler, which uses an xml object to fill ListView // inflate: fill in a new view hierarchy from the specified XML resource file // parameter: the layout ID of the View, and the root View of the generated hierarchy. // The Root View of the hierarchy filled by return. If the root parameter is provided, root is the root view; otherwise, the root of the filled XML file is the root view. ConvertView = flater. inflate (R. layout. list, null); // generate ViewHolder object viewHolder = new ViewHolder (); // assign the component in convertView to the member variable ViewHolder in viewHolder. img = (ImageView) convertView. findViewById (R. id. img); viewHolder.info = (TextView) convertView. findViewById (R.id.info); // sets the tagconvertView. setTag (viewHolder);} else {// obtain our viewHolderviewHolder = (ViewHolder) convertView from convertView. getTag ();} // Add the corresponding attribute viewHolder to the component in viewHolder. img. setBackgroundResource (R. drawable. ic_launcher); viewHolder.info. setText ("option" + datas. get (position); return convertView;} // ViewHolder class, which stores the component information. The variable value is the component information defined in xml, // when our View passes convertView = flater. inflate (R. layout. list, null); after the ViewHolder component is generated, // we can obtain the relevant information in convertView without re-inflate it, reduce memory usage class ViewHolder {private ImageView img; private TextView info;} // Add public void addItem (Integer I) {datas. add (I );}}
  
 
Xml layout of each row in ListView: Use convertView = flater. inflate (R. layout. list, null); to get the View, and then add the corresponding components to the ListView one by one,

 
     
      
      
 


4) click the button to load our data. The main method used here is adapter. notifyDataSetChanged (); it will notify the adapter of data changes.

The postDelayed method in Handler is used for code execution with a latency of 2000 milliseconds. Although the Runnable class is used, it is also running in the main thread and has not enabled another thread;

Class ButtonClickListener implements OnClickListener {@ Overridepublic void onClick (View v) {loadMore. setText ("loading data"); handler. postDelayed (new Runnable () {@ Overridepublic void run () {System. out. println ("hello"); loadData (); adapter. notifyDataSetChanged (); // listView. setSelection (5); loadMore. setText ("load more") ;}}, 2000) ;}// load data public void loadData () {int count = adapter. getCount () + 1; for (int I = count; I
 
  
5) Events in ListView:

Click an event row:

/*** Click the event triggered by one of the ListView items * @ author dell **/class OnItemListener implements OnItemClickListener {@ Overridepublic void onItemClick (AdapterView
   Arg0, View arg1, int position, long id) {System. out. println ("123 ");}}
Rolling loading event:

// Boolean isLastRow = false at the bottom of the ListView;/*** events generated during scrolling * @ author dell **/class OnScrollListener implements android. widget. absListView. onScrollListener {// always calls back when scrolling. The callback is stopped until the rolling is stopped. When you click it, the callback is called once. // firstVisibleItem: the first list item ID that is currently visible to the system (starting from 0, calculate the remaining half) // visibleItemCount: the number of items in the list that can be viewed currently (calculate the remaining half) // totalItemCount: Total number of list items @ Overridepublic void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {System. out. println ("firstVisibleItem =" + firstVisibleItem); System. out. println ("visibleItemCount =" + visibleItemCount); // determines whether to scroll to the last line if (firstVisibleItem + visibleItemCount = totalItemCount & totalItemCount> 0) {System. out. println ("the last line has been reached"); isLastRow = true;} // callback when rolling is in progress. The callback is performed two to three times. If the finger is not thrown, the callback is performed twice, scrollState = 2 this time no callback // The callback sequence is as follows: // first time: scrollState = SCROLL_STATE_TOUCH_SCROLL (1) rolling // second time: scrollState = SCROLL_STATE_FLING (2) the finger throws (the finger slides hard before leaving the screen) // The third time: scrollState = SCROLL_STATE_IDLE (0) stop scrolling // when the screen stops scrolling, It is 0; 1 When the screen is rolling and the user's touch or finger is still on the screen; // due to the user's operation, 2 @ Overridepublic void onScrollStateChanged when the screen slides in inertia (AbsListView view, int scrollState) {System. out. println ("789"); // when the last row is scrolled and the scroll is stopped, load if (isLastRow & scrollState = OnScrollListener. SCROLL_STATE_IDLE) {// execute the Loading Code isLastRow = false ;}}}

Expand knowledge point LayoutInflater:

The onCreate method always includes setContentView (R. layout. main);. You can also use LayoutInflater to load it:

SetContentView (R. layout. main); show = (Button) findViewById (R. id. btn); // The following method is equivalent to the above method // LayoutInflater layoutInflater = LayoutInflater. from (this); // View vv = layoutInflater. inflate (R. layout. main, null); // setContentView (vv); // show = (Button) vv. findViewById (R. id. btn );
The difference is:

Once setContentView () is called, layout will immediately display the UI. inflate will only form a ready-made object in the view class and display it with setContentView (view) when necessary.

Generally, the interface is displayed through setContentView () in the activity, but if you want to set the layout of the control in a non-activity, LayoutInflater needs to be dynamically loaded.

LayoutInflater notes:

/**
* LayoutInflater is used to dynamically load the content displayed on the AlertDialog page. The layout of AlertDialog is defined in custom_dialog.xml under the layout directory.
*
In actual development, the LayoutInflater class is very useful, and its function is similar to findViewById ().
The difference is that LayoutInflater is used to find and instantiate xml layout files under res/layout/, while findViewById () is to find the specific widget controls (such as Button and TextView) under the xml layout file ).
Specific functions:
1. LayoutInflater. inflate () is required for loading an interface that is not loaded or that is to be dynamically loaded;
2. For a loaded interface, you can use the Activiyt. findViewById () method to obtain the interface elements.
What is the loaded layout and what is not yet loaded. we start an application. layout related to the entry Activity {main is common. xml} is loaded, that is, in Oncreate.
Other layout objects are not loaded. They must be dynamically loaded or uploaded through another activity.

LayoutInflater is used to instantiate layout's xml layout file as a View object.
There are three methods to obtain LayoutInflater:
LayoutInflater inflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE );
View layout = inflater. inflate (R. layout. main, null );
LayoutInflater inflater = LayoutInflater. from (context); (this method is actually the first method. Refer to the source code)
View layout = inflater. inflate (R. layout. main, null );
LayoutInflater inflater = getLayoutInflater (); (this function can be used in the Activity. It is actually a function of window under the View subclass)
View layout = inflater. inflate (R. layout. main, null );
Note:
· The inflate method is different from the findViewById method;
· Inflater is used to find and instantiate xml layout files under res/layout;
· FindViewById () is used to find widgets (such as buttons and TextView) in a specific xml layout file ).
* @ Author dell
*
*/

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.