setOnScrollListener 监听
lv.setOnScrollListener(new OnScrollListener() {
/**
* 当滚动状态发生改变时 调用此方法
* 参数1:当前的ListView
* 参数2:ListView 滚动状态
* scrollState:
* SCROLL_STATE_IDLE:停止滚动的状态 常量值 0
* SCROLL_STATE_TOUCH_SCROLL:正在滚动 手指还在屏幕上 常量值 1
* SCROLL_STATE_FLING :代表滚动 形成惯性的动作 常量值 2
*
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
Log.e("AAA", "=====onScrollStateChanged==="+scrollState);
//判断到了底部并且 滚动停止 加载更多
if(isLast&&scrollState ==SCROLL_STATE_IDLE){
Toast.makeText(MainActivity.this, "加载更多", Toast.LENGTH_SHORT).show();
}
}
/**
* 当前控件滚动时 调用此方法
* 参数1:当前的ListView
* 参数2:当前屏幕展示第一条能看到的item的下标
* 参数3:屏幕展示能看到item的条数
* 参数4:listVIew 总的item数
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
Log.e("AAA", "===onScroll==firstVisibleItem"+firstVisibleItem+
"==visibleItemCount=="+visibleItemCount
+"==totalItemCount="+totalItemCount);
isLast = ((firstVisibleItem+visibleItemCount)==totalItemCount);
}
});
3,判断反悔的 图片地址和控件里的设置的标记是否是同一个
//图片异位问题
String imagePath= cookBook.getPic();
//1,给控件设置一个图片
viewHolder.iv.setImageResource(R.drawable.ic_launcher);
//2,给控件绑定下载图片的地址
viewHolder.iv.setTag(imagePath);
//判断缓存中是否有图片 如果没有 下载
if(!map.containsKey(imagePath)){
//new Callback()使用回调接口获取数据
new DownLoadImageAsyncTask(new Callback() {
@Override
public void sendResult(String imagPath, Bitmap bitmap) {
// 3,判断请求的地址和绑定的地址是否是同一个地址
if(imagPath.equals(viewHolder.iv.getTag())){
//缓存存图片
map.put(imagPath, bitmap);
viewHolder.iv.setImageBitmap(bitmap);
}
}
}).execute(cookBook.getPic());
}else{//如果有 直接从缓存中取
viewHolder.iv.setImageBitmap(map.get(imagePath));
}
getGroupCount():获取分组个数
getChildrenCount(int groupPosition):获取子元素的个数
getGroup(int groupPosition):获取当前下标分组的数据
getChild(int groupPosition, int childPosition):获取分组下标groupPosition里的子元素下标为childPosition元素的
getGroupId(int groupPosition):获取下标为groupPosition分组的id
getChildId(int groupPosition, int childPosition):获取下标为groupPosition里的子元素下标为childPosition的id
hasStableIds() :底层设计
getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent):分组的视图对象
getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent):子元素的视图对象
isChildSelectable(int groupPosition, int childPosition):子元素是否能被点击 false不能被点击 true可以被点击
有关ListView的分页加载与图文混排
MainActivity:
package com.qf.day09_listview_demo02; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AbsListView; import android.widget.Button; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import com.qf.day09_listview_demo02.adapter.MyAdapter; import com.qf.day09_listview_demo02.asynctask.MyTask; import com.qf.day09_listview_demo02.bean.CookBook; public class MainActivity extends Activity { //请求地址 private static String path ="http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page="; private ListView lv; private Button btnAddMore; private MyAdapter adapter; private MyTask myTask; private List
totalList;//存总数据 private int num = 1;//当前请求数据是第几页 //是否到底部 private boolean isLast =false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); btnAddMore = (Button) findViewById(R.id.btn_addMore); adapter = new MyAdapter(); totalList = new ArrayList (); myTask = new MyTask(MainActivity.this, totalList, adapter, num, lv); myTask.execute(path+num); lv.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if(isLast&&scrollState ==SCROLL_STATE_IDLE){ //到底部且滚动状态静止 btnAddMore.setVisibility(View.VISIBLE); }else{ btnAddMore.setVisibility(View.GONE); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 判断是否到底部 isLast = ((firstVisibleItem+visibleItemCount)==totalItemCount); } }); } //加载更多 public void MyOnclickMore(View v){ //当前页++ num++; new MyTask(MainActivity.this, totalList, adapter, num, lv) .execute(path+num); btnAddMore.setVisibility(View.GONE); } public void MyOnclic(View v){ //设置lv的位置 lv.setSelection(0); } }
HttpUtils:
package com.qf.day09_listview_demo02.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtils1 { public static byte[] getHttpResult(String path) { ByteArrayOutputStream outputStream = null; HttpURLConnection connection = null; try { URL url = new URL(path); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.connect(); outputStream = new ByteArrayOutputStream(); if (connection.getResponseCode() == 200) { InputStream iStream = connection.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = iStream.read(buffer))!=-1) { outputStream.write(buffer,0,len); outputStream.flush(); } return outputStream.toByteArray(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (outputStream!=null) { try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection!=null) { connection.disconnect(); } } return null; } }
ParseJson:
package com.qf.day09_listview_demo02.utils; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.qf.day09_listview_demo02.bean.CookBook; public class ParseJson { public static List
parsonJson(String jsonStr){ List data = new ArrayList (); try { JSONObject jsonObject = new JSONObject(jsonStr); int ret = jsonObject.getInt("ret"); if(ret==1){ JSONArray jsonArray = jsonObject.getJSONArray("data"); for(int i=0;i
Callback:
package com.qf.day09_listview_demo02.callback; import android.graphics.Bitmap; /** * * 回调接口 A类从B类里获取数据(数据需要等待) * */ public interface Callback { //参数是我的A类想获取的数据 public void sendResult(String imagPath,Bitmap bitmap); }
CookBook:package com.qf.day09_listview_demo02.bean; public class CookBook { // "title": "油焖大虾", // "pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg", private String title; private String pic; public CookBook(String title, String pic) { super(); this.title = title; this.pic = pic; } public CookBook() { super(); // TODO Auto-generated constructor stub } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } }
DownLoaderImageAsyncTask:package com.qf.day09_listview_demo02.asynctask; import com.qf.day09_listview_demo02.callback.Callback; import com.qf.day09_listview_demo02.utils.HttpUtils1; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.widget.ImageView; public class DownLoadImageAsyncTask extends AsyncTask
{ // private ImageView iv; // public DownLoadImageAsyncTask(ImageView iv){ // this.iv = iv; // } private Callback callback; public DownLoadImageAsyncTask(Callback callback){ this.callback = callback; } private String imagePath =""; @Override protected Bitmap doInBackground(String... params) { // TODO Auto-generated method stub imagePath = params[0]; byte[] buffer = HttpUtils1.getHttpResult(imagePath); if(buffer!=null&&buffer.length>0){ Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length); return bitmap; } return null; } @Override protected void onPostExecute(Bitmap result) { // TODO Auto-generated method stub super.onPostExecute(result); //更新UI //数据被回调接口回调回来(鱼咬钩了) callback.sendResult(imagePath, result); // if(result!=null){ // iv.setImageBitmap(result); // } } }
MyTask :package com.qf.day09_listview_demo02.asynctask; import java.util.List; import android.R; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.widget.ListView; import android.widget.Toast; import com.qf.day09_listview_demo02.adapter.MyAdapter; import com.qf.day09_listview_demo02.bean.CookBook; import com.qf.day09_listview_demo02.utils.HttpUtils1; import com.qf.day09_listview_demo02.utils.ParseJson; public class MyTask extends AsyncTask
>{ private Context context; private List totalList; private MyAdapter adapter; private int num; private ListView lv; private ProgressDialog progressDialog; public MyTask(Context context,List totalList,MyAdapter adapter,int num,ListView lv){ this.context = context; this.totalList = totalList; this.adapter = adapter; this.num = num; this.lv = lv; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); progressDialog = new ProgressDialog(context); progressDialog.setTitle("好吃的"); progressDialog.setIcon(R.drawable.alert_dark_frame); progressDialog.setMessage("正在吃...."); progressDialog.setCancelable(false); progressDialog.show(); } @Override protected List doInBackground(String... params) { // TODO Auto-generated method stub //下载数据 String path = params[0]; byte[] buffer = HttpUtils1.getHttpResult(path); String jsonStr = new String(buffer, 0, buffer.length); //解析数据 return ParseJson.parsonJson(jsonStr); } @Override protected void onPostExecute(List result) { // TODO Auto-generated method stub super.onPostExecute(result); progressDialog.dismiss(); //更新UI if(result!=null&&result.size()>0){ //存总的数据 1,2,3... totalList.addAll(result); //判断是否是第一页 是第一页 使用setAdapter()将adapter设置给lv, //如果不是第一页刷新界面将所有数据展示到lvnotifyDataSetChanged(); if(num ==1){ adapter.setList(context, totalList); lv.setAdapter(adapter); }else{ adapter.setList(context, totalList); adapter.notifyDataSetChanged(); } }else{ Toast.makeText(context, "网络异常, 请稍等..",Toast.LENGTH_SHORT).show(); } } }
MyAdapter :
package com.qf.day09_listview_demo02.adapter; import java.util.HashMap; import java.util.List; import java.util.Map; import com.qf.day09_listview_demo02.R; import com.qf.day09_listview_demo02.asynctask.DownLoadImageAsyncTask; import com.qf.day09_listview_demo02.bean.CookBook; import com.qf.day09_listview_demo02.callback.Callback; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class MyAdapter extends BaseAdapter { private Context context; private List
data; //假设是 一个缓存器 private Map map = new HashMap (); //自定义一个方法传数据 public void setList(Context context,List data){ this.context = context; this.data = data; } @Override public int getCount() { // TODO Auto-generated method stub return data==null?0:data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return data.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder viewHolder ; if(convertView ==null){ convertView = LayoutInflater.from(context) .inflate(R.layout.item, parent, false); viewHolder = new ViewHolder(); viewHolder.iv = (ImageView) convertView.findViewById(R.id.iv_item); viewHolder.tv = (TextView) convertView.findViewById(R.id.tv_item); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } CookBook cookBook = data.get(position); viewHolder.tv.setText(cookBook.getTitle()); //图片 // DownLoadImageAsyncTask downLoadImageAsyncTask = // new DownLoadImageAsyncTask(viewHolder.iv); // downLoadImageAsyncTask.execute(cookBook.getPic()); //图片异位问题 String imagePath= cookBook.getPic(); //1,给控件设置一个图片 viewHolder.iv.setImageResource(R.drawable.ic_launcher); //2,给控件绑定下载图片的地址 viewHolder.iv.setTag(imagePath); //判断缓存中是否有图片 如果没有 下载 if(!map.containsKey(imagePath)){ //new Callback()使用回调接口获取数据 new DownLoadImageAsyncTask(new Callback() { @Override public void sendResult(String imagPath, Bitmap bitmap) { // 3,判断请求的地址和绑定的地址是否是同一个地址 if(imagPath.equals(viewHolder.iv.getTag())){ //缓存存图片 map.put(imagPath, bitmap); viewHolder.iv.setImageBitmap(bitmap); } } }).execute(cookBook.getPic()); }else{//如果有 直接从缓存中取 viewHolder.iv.setImageBitmap(map.get(imagePath)); } return convertView; } class ViewHolder{ ImageView iv; TextView tv; } }