Android中ScrollView中放Listview自适应高度示例
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2015-07-17 17:15:49
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
实现过程是scrollview包含着一个listview监听scrollview滚动到底边时开始向listview中添加数据
加载图片用到啦 universalimageloader 请自行引入下载地址在 http://www.zhaokeli.com/Article/6276.html
下面是一张效果图(里面用的是json加载数据使用的时候请更换成自己的数据)
首先是布局文件activity_home.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/white" android:orientation="vertical" > <ScrollView android:id="@+id/scrollid" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!--产品列表 --> <ListView android:id="@+id/goodslist" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/white" android:cacheColorHint="@android:color/transparent" android:divider="@color/border" android:dividerHeight="1px" android:listSelector="@drawable/list_item_selector" > </ListView> <TextView android:id="@+id/loading" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical|center" android:background="@color/white" android:textColor="@color/black" android:text="@string/loading" android:visibility="gone" /> </LinearLayout> </ScrollView> </LinearLayout>
下面是列表的适配器HomeGoodsListViewAdapter.java
package com.demo.adapter; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.demo.core.AsyncImageLoader; import com.demo.jiuwo.R; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache; import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.ImageSize; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.decode.BaseImageDecoder; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; import com.nostra13.universalimageloader.core.imageaware.ImageAware; import com.nostra13.universalimageloader.core.imageaware.ImageViewAware; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.nostra13.universalimageloader.utils.StorageUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.os.Handler; import android.support.v4.util.LruCache; import android.util.Log; 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 HomeGoodsListViewAdapter extends BaseAdapter { static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); private Context context; //运行上下文 private List<Map<String, Object>> listItems; //商品信息集合 private LayoutInflater listContainer; //视图容器 public final class ListItemView{ //自定义控件集合 public TextView title; public TextView price; public TextView goodsid; public ImageView image; } public HomeGoodsListViewAdapter(Context context) { this.context = context; listContainer = LayoutInflater.from(context); //创建视图容器并设置上下文 this.listItems=new ArrayList<Map<String, Object>>(); } public HomeGoodsListViewAdapter(Context context, List<Map<String, Object>> listItems) { this.context = context; listContainer = LayoutInflater.from(context); //创建视图容器并设置上下文 this.listItems = listItems; } public void addItem(Map<String,Object> o){ listItems.add(o); } public int getCount() { // TODO Auto-generated method stub return listItems.size(); } public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } /** * ListView Item设置 */ public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //自定义视图 ListItemView listItemView = null; if (convertView == null) { listItemView = new ListItemView(); //获取list_item布局文件的视图 convertView = listContainer.inflate(R.layout.home_goodslist_item, null); //获取控件对象 listItemView.title = (TextView)convertView.findViewById(R.id.titleItem); listItemView.price = (TextView)convertView.findViewById(R.id.price); listItemView.image = (ImageView)convertView.findViewById(R.id.imageItem); listItemView.goodsid = (TextView)convertView.findViewById(R.id.goodsid); //设置控件集到convertView convertView.setTag(listItemView); }else{ listItemView = (ListItemView)convertView.getTag(); } //设置文字和图片 String imgurl=(String) listItems.get(position).get("pic"); loadBitmap(imgurl,listItemView.image,R.drawable.default_ico); listItemView.goodsid.setText((String) listItems.get(position) .get("goodsid")); listItemView.title.setText((String) listItems.get(position) .get("title")); listItemView.price.setText((String) listItems.get(position) .get("price")); return convertView; } /** * * @param urlStr 所需要加载的图片的url,以String形式传进来,可以把这个url作为缓存图片的key * @param image ImageView 控件 * @param resId 默认显示的图片资源 */ private void loadBitmap(String urlStr, ImageView image,int resId) { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.default_ico) // 设置图片在下载期间显示的图片 .showImageForEmptyUri(R.drawable.default_ico)// 设置图片Uri为空或是错误的时候显示的图片 .showImageOnFail(R.drawable.default_ico)// 设置图片加载/解码过程中错误时候显示的图片 .resetViewBeforeLoading(true) // default .delayBeforeLoading(1000) .cacheInMemory(true)//设置下载的图片是否缓存在内存中 .cacheOnDisk(true) //设置下载的图片是否缓存在SD卡中 // .postProcessor(null)//在图片显示之前的操作 //.preProcessor(null) //设置图片加入缓存前,对bitmap进行设置 .extraForDownloader(null) .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default // .decodingOptions(null) .displayer(new SimpleBitmapDisplayer()) // default .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角,弧度为多少 //.displayer(new FadeInBitmapDisplayer(100))//最好不添加会出现闪烁的情况 .handler(new Handler()) // default .build(); //返回一个实例 ImageLoader imageLoader = ImageLoader.getInstance(); //ImageAware imageAware = new ImageViewAware(image, false); //imageLoader.displayImage(urlStr,image,options); //ImageSize targetSize = new ImageSize(150, 150); // result Bitmap will be fit to this size //image.setImageBitmap(imageLoader.loadImageSync(urlStr, targetSize, options));//同步加载 imageLoader.displayImage(urlStr, image, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap Log.v("catch",view+""); try{ if (loadedImage != null && view!=null) { ImageView imageView = (ImageView) view; // imageView.setImageBitmap(loadedImage); // 是否第一次显示 boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { // 图片淡入效果 FadeInBitmapDisplayer.animate(imageView, 800); displayedImages.add(imageUri); } } }catch(Exception e){ Log.v("catch1",e.getMessage()); } } }); } }
下面是HomeActivity.java
package com.demo.jiuwo.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.baidu.android.pushservice.PushConstants; import com.baidu.android.pushservice.PushManager; import com.demo.adapter.GridViewAdapter; import com.demo.adapter.HomeGoodsListViewAdapter; import com.demo.jiuwo.BaseActivity; import com.demo.jiuwo.R; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageSwitcher; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView.OnItemClickListener; public class HomeActivity extends BaseActivity { protected WebView webview; private boolean okload;//标记是否可以加载 protected ListView goodslistview; private ScrollView mScrollView; protected TextView loading; protected ArrayList<Map<String, Object>> goodslistItems; //产品列表 private HomeGoodsListViewAdapter goodslistviewadapter; //产品适配器 @Override protected void onCreate(Bundle savedInstanceState) { okload=true; super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); goodslistview = (ListView) findViewById(R.id.goodslist); mScrollView= (ScrollView) findViewById(R.id.scrollid); loading= (TextView) findViewById(R.id.loading); initListener(); //后台请求产品列表 loaddata(); } private void loaddata(){ new Thread(new Runnable() { public void run() { okload=false; runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub loading.setVisibility(View.VISIBLE); } }); try{ boolean firstload=false; int count=0; if(goodslistviewadapter == null){ firstload=true; goodslistviewadapter = new HomeGoodsListViewAdapter(HomeActivity.this); //创建适配器 }else{ count = goodslistviewadapter.getCount(); } //后台请求产品列表 // TODO Auto-generated method stub String jsonstr=getUrlPage("填写上你自己的json地址"); if(jsonstr!=""){ try{ JSONArray jsonarr= new JSONObject(jsonstr).getJSONArray("goods_list"); for(int i = 0; i < jsonarr.length() ; i++){ JSONObject jsonObj = ((JSONObject)jsonarr.opt(i)); int id = jsonObj.getInt("id"); String pic = jsonObj.getString("pic"); String title = jsonObj.getString("title"); String price = jsonObj.getString("price"); Map<String, Object> map = new HashMap<String, Object>(); map.put("pic", pic); map.put("title", title); map.put("price", price); map.put("id", id); if(!map.isEmpty()){ goodslistviewadapter.addItem(map); } } if(firstload){ runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub goodslistview.setAdapter(goodslistviewadapter); } }); } Log.v("adapter_count",goodslistviewadapter.toString()); // 发送消息 handler.sendMessage(handler.obtainMessage(100, null)); //goodslistview.setSelection(lastItem - 1); }catch(JSONException e){ Log.v("json_err",e.getMessage()); } }else{ Toast.makeText(getApplicationContext(), "已经没有内容啦!", Toast.LENGTH_SHORT).show(); } }catch(Exception e){ Log.v("json_err",e.getMessage()); } } }).start(); } //动态设置listview的高度 public void setListViewHeightBasedOnChildren(ListView listView) { // 获取ListView对应的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount()-1)); ((MarginLayoutParams)params).setMargins(10, 10, 10, 10); listView.setLayoutParams(params); } /** * 初始化事件绑定 **/ private void initListener(){ goodslistview.setOnItemClickListener(new OnItemClickListener(){ @Override //arg0:就是你的listview arg2:点击的item的位置。和你的数组的下标相等。arg3:被电击view的id public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub // TODO Auto-generated method stub try{ Map<String, Object> map=goodslistItems.get(arg2); String titleitem=map.get("id").toString(); Intent intent=new Intent(); Bundle bundle=new Bundle(); bundle.putString("goodsid",titleitem); intent.putExtras(bundle); intent.setClass(HomeActivity.this,GoodsActivity.class); startActivity(intent); finish(); inright(); }catch(Exception e){ e.printStackTrace(); } } }); //scrollview滚动到底部监听 mScrollView.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub switch (arg1.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: int scrollY=arg0.getScrollY(); int height=arg0.getHeight(); int scrollViewMeasuredHeight=mScrollView.getChildAt(0).getMeasuredHeight(); if(scrollY==0){ System.out.println("滑动到了顶端 view.getScrollY()="+scrollY); } if((scrollY+height)==scrollViewMeasuredHeight){ System.out.println("滑动到了底部 scrollY="+scrollY); System.out.println("滑动到了底部 height="+height); System.out.println("滑动到了底部 scrollViewMeasuredHeight="+scrollViewMeasuredHeight); if(okload){ loaddata(); } } break; default: break; } return false; } }); } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { //通知listview更新界面 goodslistviewadapter.notifyDataSetChanged(); loading.setVisibility(View.GONE); setListViewHeightBasedOnChildren(goodslistview); okload=true;//可以再次加载 }; }; }