Listview动态加载网络数据Activity大概实现

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. /** Called when the activity is first created. */
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. //list_View.removeFooterView(loadMoreView);
106. Toast.makeText(this"数据全部加载完!", Toast.LENGTH_LONG).show();
107. }
108. }
109.  
110. /**
111. * 初始化ListView的适配器
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. //DialogUtil.showDialog(this,ReturnStr, false);
120. JSONArray jsonArray;
121. // DialogUtil.showDialog(this, ReturnStr, false);
122. if (ReturnStr.contentEquals("anyType{}")) {
123. jsonArray = new JSONArray();
124. else {
125. jsonArray = new JSONArray(ReturnStr);
126. }
127. // 向指定URL发送请求,并把服务器响应转换成JSONArray对象
128.  
129. // 将JSONArray包装成Adapter
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. //DialogUtil.showDialog(this, e.getMessage(), false);
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. // DialogUtil.showDialog(this, ReturnStr, false);
162. if (ReturnStr.contentEquals("anyType{}")) {
163. jsonArray = new JSONArray();
164. else {
165. jsonArray = new JSONArray(ReturnStr);
166. }
167. // 向指定URL发送请求,并把服务器响应转换成JSONArray对象
168.  
169. // 将JSONArray包装成Adapter
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. //DialogUtil.showDialog(this, e.getMessage(), false);
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. * @param newsitem
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值