ListView分批动态加载Item

这个例子主要实现ListView当滚动完毕所有可见Item后,继续加载未显示item例子,主要通过onScroll的监听来实现:

package com.example.listview;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;

public class ListViewLoading extends ListActivity implements OnScrollListener {

private ProgressBar progressBar;

private LayoutParams WClayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);

private ListViewAdapter adapter = new ListViewAdapter();

class ListViewAdapter extends BaseAdapter {
int count = 5;

public int getCount() {
return count;
}

public Object getItem(int pos) {
return pos;
}

public long getItemId(int pos) {
return pos;
}

public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(ListViewLoading.this);
view.setText("The item position " + pos);
view.setTextSize(20f);
view.setHeight(80);
return view;
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
progressBar = new ProgressBar(this);
progressBar.setPadding(0, 0, 15, 0);
layout.addView(progressBar, WClayoutParams);

TextView textView = new TextView(this);
textView.setText("数据加载中...");
textView.setGravity(Gravity.CENTER_VERTICAL);

layout.addView(textView, FFlayoutParams);
layout.setGravity(Gravity.CENTER);

LinearLayout loadingLayout = new LinearLayout(this);
loadingLayout.addView(layout, WClayoutParams);
loadingLayout.setGravity(Gravity.CENTER);

ListView listView = getListView();
listView.addFooterView(loadingLayout);
setListAdapter(adapter);
listView.setOnScrollListener(this);
// registerForContextMenu(listView);
}

private int lastItem = 0;

// 每次ListView被滚动时调用
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
if (lastItem == adapter.count
&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
adapter.count += 3;
adapter.notifyDataSetChanged();
}
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
lastItem = firstVisibleItem + visibleItemCount - 1;
System.out.println("firstVisibleItem:" + firstVisibleItem);
System.out.println("visibleItemCount:" + visibleItemCount);
}
}

你可能感兴趣的:(Android组件学习)