Friday, 14 February 2014

Page auto-load when scroll in android example

Page auto-load when scroll in android example

              This is the sample coding for create page auto load when scroll the listview in android.

For do that first you have to create the listview and set the array of values into the listview using the ArrayAdapter


list=new ArrayList<String>();
 lv=(ListView)findViewById(R.id.listView1);

 for(int i=0;i<35;i++){
 list.add(String.valueOf(i));
 }
 final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
 android.R.layout.simple_list_item_1, list) {
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 View view = super.getView(position, convertView, parent);
 TextView text = (TextView) view.findViewById(android.R.id.text1);
 text.setTextColor(Color.BLACK);
 return view;
 }
 };
 lv.setAdapter(adapter);


Then,set the OnScrollListener() for the listview.




lv.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
Log.d("SCROLL STATE", String.valueOf(scrollState));
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});


Inside OnScrollListener you have to get the firstVisibleItem, visibleItemCount in onScroll
to get the current visible items and load the more item and set it in to the listview.



Log.d("visibleItemCount", String.valueOf(visibleItemCount));
Log.d("firstVisibleItem", String.valueOf(firstVisibleItem));
// Log.d("totalItemCount", String.valueOf(totalItemCount));
if(firstVisibleItem+visibleItemCount>30)
{

list.clear();
for(int i=0;i<=100;i++){
list.add(String.valueOf(i));
}
adp.notifyDataSetChanged();
}




Screenshot:


No comments: