Android listview Dynamic Loading List Item Implementation Code

  • 2021-07-22 11:26:01
  • OfStack

Recently, I have a column that dynamically loads listview class entries, and shared it for everyone to learn. Tell me about the implementation process of this example. First, I limit the list item data loaded each time to 10 pieces of data. When dragging listview to scroll to the last piece of data, I load another 10 pieces of data, and display the loading prompt below Listview.

Here's my java source:


private void showContent() { 
  listView = (ListView) findViewById(R.id.journals_list_one); 
  loadData(); 
  adapter = new MyListAdapter(this, data); 
 
  footerView = View.inflate(TestLayout.this, 
    R.layout.journal_listitem_loading_bar, null); 
  listView.addFooterView(footerView, null, true); 
 
  listView.setAdapter(adapter); 
  listView.setOnScrollListener(listener); 
 } 
private AbsListView.OnScrollListener listener = new AbsListView.OnScrollListener() { 
 
  @Override 
  public void onScrollStateChanged(AbsListView view, int scrollState) { 
   if (view.getLastVisiblePosition() == view.getCount() - 1) { 
    loadData(); 
    adapter.notifyDataSetChanged(); 
   } 
  } 
 
  @Override 
  public void onScroll(AbsListView view, int firstVisibleItem, 
    int visibleItemCount, int totalItemCount) { 
 
  } 
 }; 
 
 /** 
  *  Structure List List data  
  */ 
 private void loadData() { 
  if (data.size() <= 40) { 
   for (int i = 0; i < 10; i++) { 
    Map<String, String> map = new HashMap<String, String>(); 
    map.put("title", getString(R.string.title)); 
    map.put("desc", getString(R.string.content)); 
    data.add(map); 
   } 
  } else { 
   listView.removeFooterView(footerView); 
  } 
 } 

To achieve this function is mainly to add ListView OnScrollListener monitoring, judging whether the list of items to the most one, if it is the last one to load data. The loading effect when loading data is that the ListView. addFooterView () method is implemented. This method must be useful before listview. setAdapter (). When all data is loaded, call listView. removeFooterView to remove footerview.

If you want to learn more about Android listview, you can click to view the topic, which is more exciting: how to use Android listview


Related articles: