Listview动态加载网络数据 总体框架: 1.滚动加载 listView.setOnScrollListener(new OnScrollListener() { //添加滚动条滚到最底部,加载余下的元素 @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { loadRemnantListItem(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {} }); listView.setOnItemSelectedListener(new OnItemSelectedListener() { //按键选择List中的item,焦点落在最下面的view上加载余下的item //类似于微博客户端在底部有个更多的选项footerView ,然后点击加载。 @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(footerView == view) { loadRemnantListItem(); listView.setSelection(position - 1); } } @Override publicvoid onNothingSelected(AdapterView<?> parent) {} }); privatevoid loadRemnantListItem() {//滚到加载余下的数据 //动态的改变listAdapter.getCount()的返回值 //使用Handler调用listAdapter.notifyDataSetChanged();更新数据 } 2.滚动翻页 //listView监听器代码相同 privatevoid loadRemnantListItem() {//滚到加载余下的数据 //重新listView.setAdapter(newsAdapter); //使用Handler调用listAdapter.notifyDataSetChanged();更新数据 } 注:在listView最下面可以使用listView.addFooterView(footerView, null, true);来显示“加载中...”等的字样来美化用户体验,在loadRemnantListItem()方法中动态控制“加载中...”的显示和不显示。 实例:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;
public class ListViewForLoading extends Activity implements OnScrollListener {
private listViewAdapter adapter = new listViewAdapter();
ListView listView;
LinearLayout loadingLayout;
private Thread mThread;
/**
* 设置布局显示属性
*/
private LayoutParams mLayoutParams = 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 ProgressBar progressBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// TODO Auto-generated method stub
// 线性布局
LinearLayout layout = new LinearLayout(this);
// 设置布局 水平方向
layout.setOrientation(LinearLayout.HORIZONTAL);
// 进度条
progressBar = new ProgressBar(this);
// 进度条显示位置
progressBar.setPadding(0, 0, 15, 0);
// 把进度条加入到layout中
layout.addView(progressBar, mLayoutParams);
// 文本内容
TextView textView = new TextView(this);
textView.setText("加载中...");
textView.setGravity(Gravity.CENTER_VERTICAL);
// 把文本加入到layout中
layout.addView(textView, FFlayoutParams);
// 设置layout的重力方向,即对齐方式是
layout.setGravity(Gravity.CENTER);
// 设置ListView的页脚layout
loadingLayout = new LinearLayout(this);
loadingLayout.addView(layout, mLayoutParams);
loadingLayout.setGravity(Gravity.CENTER);
// 得到一个ListView用来显示条目
listView = (ListView) findViewById(R.id.tv);
// 添加到脚页显示
listView.addFooterView(loadingLayout);
// 给ListView添加适配器
listView.setAdapter(adapter);
// 给ListView注册滚动监听
listView.setOnScrollListener(this);
}
/**
* 要用用于生成显示数据
*
* @author huangbq
*
*/
class listViewAdapter extends BaseAdapter {
int count = 10;
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;
if (v == null) {
view = new TextView(ListViewForLoading.this);
} else {
view = (TextView) v;
}
view.setText("ListItem " + pos);
view.setTextSize(20f);
view.setGravity(Gravity.CENTER);
view.setHeight(60);
return view;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(firstVisibleItem+visibleItemCount==totalItemCount)
{
//开线程去下载网络数据
if (mThread == null || !mThread.isAlive()) {
mThread = new Thread() {
@Override
public void run() {
try {
//这里放你网络数据请求的方法,我在这里用线程休眠5秒方法来处理
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
mThread.start();
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case 1:
if (adapter.count <= 41) {
adapter.count += 10;
int currentPage = adapter.count / 10;
Toast.makeText(getApplicationContext(),"第" + currentPage + "页", Toast.LENGTH_LONG).show();
} else {
listView.removeFooterView(loadingLayout);
}
//重新刷新Listview的adapter里面数据
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
}
运行结果如下图: 实例2:
package com.jemsn.android;
002.
003.
004.
import java.util.ArrayList;
005.
import java.util.List;
006.
007.
import org.json.JSONArray;
008.
009.
import com.jemsn.util.DialogUtil;
010.
import com.jemsn.util.Goods;
011.
import com.jemsn.util.WebServiceUtil;
012.
013.
import android.app.Activity;
014.
import android.os.Bundle;
015.
import android.os.Handler;
016.
import android.util.Log;
017.
import android.view.View;
018.
import android.view.ViewGroup;
019.
import android.widget.AbsListView;
020.
import android.widget.AbsListView.OnScrollListener;
021.
import android.widget.BaseAdapter;
022.
import android.widget.Button;
023.
import android.widget.EditText;
024.
import android.widget.ListView;
025.
import android.widget.TextView;
026.
import android.widget.Toast;
027.
028.
public class AndroidQueryActivity extends Activity implements OnScrollListener {
029.
030.
private ListView list_View;
031.
private int visibleLastIndex = 0 ;
032.
private int visibleItemCount;
033.
private int datasize = 100 ;
034.
private PaginationAdapter adapter;
035.
private View loadMoreView;
036.
private Button loadMoreButton,Search_Btn;
037.
private Handler handler = new Handler();
038.
private EditText SearcText;
039.
040.
041.
@Override
042.
public void onCreate(Bundle savedInstanceState) {
043.
super .onCreate(savedInstanceState);
044.
setContentView(R.layout.view_item);
045.
SearcText = (EditText) findViewById(R.id.text_SeGds);
046.
Search_Btn=(Button)findViewById(R.id.BtnGoods_Search);
047.
loadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null );
048.
loadMoreButton = (Button) loadMoreView
049.
.findViewById(R.id.loadMoreButton);
050.
loadMoreButton.setOnClickListener( new View.OnClickListener() {
051.
@Override
052.
public void onClick(View v) {
053.
loadMoreButton.setText( "正在加载中..." );
054.
handler.postDelayed( new Runnable() {
055.
056.
@Override
057.
public void run() {
058.
loadMoreData();
059.
adapter.notifyDataSetChanged();
060.
Toast.makeText(AndroidQueryActivity. this , "数据加载完!" , Toast.LENGTH_LONG).show();
061.
loadMoreButton.setText( "查看更多..." );
062.
}
063.
}, 2000 );
064.
065.
}
066.
});
067.
Search_Btn.setOnClickListener( new View.OnClickListener() {
068.
069.
@Override
070.
public void onClick(View v) {
071.
initializeAdapter();
072.
list_View.setAdapter(adapter);
073.
}
074.
});
075.
076.
list_View = (ListView)findViewById(R.id.GoodsList);
077.
078.
list_View.addFooterView(loadMoreView);
079.
Log.e( "WangYOUHellow" , "Goods" );
080.
initializeAdapter();
081.
082.
list_View.setAdapter(adapter);
083.
Log.e( "WangYOUHellow" , "Hellow" );
084.
list_View.setOnScrollListener( this );
085.
}
086.
087.
@Override
088.
public void onScrollStateChanged(AbsListView view, int scrollState) {
089.
int itemsLastIndex = adapter.getCount() - 1 ;
090.
int lastIndex = itemsLastIndex + 1 ;
091.
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
092.
&& visibleLastIndex == lastIndex) {
093.
094.
}
095.
}
096.
097.
@Override
098.
public void onScroll(AbsListView view, int firstVisibleItem,
099.
int visibleItemCount, int totalItemCount) {
100.
this .visibleItemCount = visibleItemCount;
101.
visibleLastIndex = firstVisibleItem + visibleItemCount - 1 ;
102.
103.
104.
if (totalItemCount == datasize + 1 ) {
105.
106.
Toast.makeText( this , "数据全部加载完!" , Toast.LENGTH_LONG).show();
107.
}
108.
}
109.
110.
111.
112.
113.
private void initializeAdapter() {
114.
Log.e( "WangYOUHellow" , "Bad" );
115.
try {
116.
String Parame = SearcText.getText().toString();
117.
String ReturnStr = WebServiceUtil
118.
.getCityListByProvince(Parame, "1" );
119.
120.
JSONArray jsonArray;
121.
122.
if (ReturnStr.contentEquals( "anyType{}" )) {
123.
jsonArray = new JSONArray();
124.
} else {
125.
jsonArray = new JSONArray(ReturnStr);
126.
}
127.
128.
129.
130.
List<Goods> GoodsArry = new ArrayList<Goods>();
131.
132.
for ( int i = 0 ; i<jsonArray.length(); i++) {
133.
Goods items = new Goods();
134.
items.setGds_Name(jsonArray.optJSONObject(i).getString(
135.
"GdsName" ));
136.
items.setGds_Code(jsonArray.optJSONObject(i).getString(
137.
"GdsCode" ));
138.
GoodsArry.add(items);
139.
}
140.
adapter = new PaginationAdapter(GoodsArry);
141.
} catch (Exception e) {
142.
143.
e.printStackTrace();
144.
}
145.
146.
}
147.
148.
149.
150.
151.
private void loadMoreData() {
152.
int count = adapter.getCount();
153.
154.
try {
155.
156.
String Parame = SearcText.getText().toString();
157.
String pageSize = String.valueOf(count / 10 + 1 );
158.
String ReturnStr = WebServiceUtil.getCityListByProvince(Parame,
159.
pageSize);
160.
JSONArray jsonArray;
161.
162.
if (ReturnStr.contentEquals( "anyType{}" )) {
163.
jsonArray = new JSONArray();
164.
} else {
165.
jsonArray = new JSONArray(ReturnStr);
166.
}
167.
168.
169.
170.
for ( int i = 1 ; jsonArray.length() <= 10 ; i++) {
171.
Goods items = new Goods();
172.
items.setGds_Name(jsonArray.optJSONObject(i).getString(
173.
"GdsName" ));
174.
items.setGds_Code(jsonArray.optJSONObject(i).getString(
175.
"GdsCode" ));
176.
adapter.addNewsItem(items);
177.
}
178.
} catch (Exception e) {
179.
180.
e.printStackTrace();
181.
}
182.
183.
}
184.
185.
class PaginationAdapter extends BaseAdapter {
186.
187.
List<Goods> newsItems;
188.
189.
public PaginationAdapter(List<Goods> newsitems) {
190.
this .newsItems = newsitems;
191.
}
192.
193.
@Override
194.
public int getCount() {
195.
return newsItems.size();
196.
}
197.
198.
@Override
199.
public Object getItem( int position) {
200.
return newsItems.get(position);
201.
}
202.
203.
@Override
204.
public long getItemId( int position) {
205.
return position;
206.
}
207.
208.
@Override
209.
public View getView( int position, View view, ViewGroup parent) {
210.
if (view == null ) {
211.
view = getLayoutInflater().inflate(R.layout.list_item, null );
212.
}
213.
214.
215.
TextView tvGdsName = (TextView) view.findViewById(R.id.Gds_Name);
216.
tvGdsName.setText(newsItems.get(position).getGds_Name());
217.
218.
TextView tvGdsCode = (TextView) view.findViewById(R.id.Gds_Code);
219.
tvGdsCode.setText(newsItems.get(position).getGds_Code());
220.
221.
return view;
222.
}
223.
224.
225.
226.
227.
228.
229.
public void addNewsItem(Goods newsitem) {
230.
newsItems.add(newsitem);
231.
}
232.
233.
}
234.
235.
}
参考文章: http://www.cnblogs.com/Greenwood/archive/2011/04/02/2003170.html http://www.it165.net/pro/html/201112/1434.html http://www.cnblogs.com/tanlon/archive/2011/03/20/1989323.html |