Monthly Archives: August 2012

Android Dynamic listview updates and append

I just finished my android code on generating never ending listview and just want to share what I have. It will be nice if someone out there can help me recycle my listview properly. This is not a complete solution, but should be good enough for someone to pick up the idea on how to implement it.

I will create a layout for my footer to go into

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:gravity="center_horizontal"
 android:padding="3dp"
 android:layout_height="fill_parent">
 <TextView
 android:id="@+id/listfooter"
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:gravity="center"
 android:padding="8dp"
 android:textStyle="bold"
 android:text="Loading more items..."/>
</LinearLayout>

Then, you will need to append the footer to your listview. In my case I put it under my onCreate();

lv = (ListView)findViewById(R.id.getdish_list);
lv.addFooterView(((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listviewfooter, null, false));

Now we need to set our listview listener so when it reach our footer view, it can grab additional items.

lv.setSelection(listviewselection); // This line is to position your list view so it does not jump to first in list after updating.
lv.setOnScrollListener(new OnScrollListener(){
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

//get the last item that is visible on the screen
int lastItemInScreen = firstVisibleItem + visibleItemCount;

//I set a flag here to ask if the list require more items from the server
if((lastItemInScreen == totalItemCount) && flg_shouldLoad){

flg_shouldLoad = false;
listviewselection = firstVisibleItem;
Thread thread = new Thread(null, loadMoreItems);
thread.start();
}
}
});

Following, I will need a runnable to get my item from my server


//Runnable to load the items
private Runnable loadMoreItems = new Runnable() {
@Override
public void run() {
getMoreItem();
}};

At last make sure you do a check for onclicklistener for listview to ignore the last item of your adapter, so you will not have a indexoutofbound exception.

Advertisements