Created
October 8, 2015 18:16
-
-
Save deepak786/3c909159be8168ef9a25 to your computer and use it in GitHub Desktop.
How to use ListView OnScroll to load item when we reach end of the ListView.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.widget.AbsListView; | |
import android.widget.AbsListView.OnScrollListener; | |
import android.widget.ArrayAdapter; | |
import android.widget.ListView; | |
public class MainActivity extends AppCompatActivity { | |
ListView list; | |
ArrayList<String> al ; | |
ArrayAdapter<String> aa; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
list = (ListView) findViewById(R.id.list); | |
al = new ArrayList<>(); | |
addItems(); | |
aa = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, al); | |
list.setAdapter(aa); | |
list.setOnScrollListener(new OnScrollListener() { | |
@Override | |
public void onScrollStateChanged(AbsListView view, int scrollState) { | |
} | |
@Override | |
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { | |
System.out.println(firstVisibleItem+"---"+visibleItemCount+"---"+totalItemCount); | |
// add more items to listview when there are two items remaining at the scroll end. | |
if(firstVisibleItem + visibleItemCount >= totalItemCount-2){ | |
addItems(); | |
aa.notifyDataSetChanged(); | |
} | |
} | |
}); | |
} | |
public void addItems(){ | |
int size = al.size(); | |
for(int i=size;i<(size+10);i++){ | |
al.add("List item "+(i+1)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment