Android初级教程_图片混排效果和ViewPager的使用

前段时间公司需要实现图片混排的效果,类似"美丽说"那样,宽度一样,高度不一.总共有3列.每次加载更多的时候都是往最低的那列添加图片,这样就不会出现有的列非常多的图片,而有的列图片很少.首先申明的是这个例子是根据别人的程序基础上改的:https://github.com/dodola/android_waterfall再次感谢.!

效果如下图所示:


Android初级教程_图片混排效果和ViewPager的使用_第1张图片


当滑倒底部的时候如果还有图片则自动加载下一页.

代码实现如下:

首先自定义布局:

[java] view plain copy
  1. public class MyLinearLayout extends LinearLayout {  
  2.   
  3.     private Map<Integer, Integer> map;  
  4.     private ArrayList<LinearLayout> waterfall_items;  
  5.     private Context context;  
  6.     private Display display;  
  7.     private int itemWidth;  
  8.   
  9.     public MyLinearLayout(Context context, AttributeSet attrs) {  
  10.         super(context, attrs);  
  11.     }  
  12.     public MyLinearLayout(Context context) {  
  13.         super(context);  
  14.     }  
  15.   
  16.     /** 
  17.      * 初始化容器  
  18.      * @param columnCount 
  19.      *            列数 
  20.      * @param paddingLeft 
  21.      * @param paddingTop 
  22.      * @param paddingRight 
  23.      * @param paddingBottom 
  24.      */  
  25.     public void initLayout(int columnCount, int paddingLeft, int paddingTop,  
  26.             int paddingRight, int paddingBottom) {  
  27.           
  28.         if (columnCount < 1)  
  29.             columnCount = 3;  
  30.           
  31.         Constans.COLUMN_COUNT = columnCount;  
  32.           
  33.         waterfall_items = new ArrayList<LinearLayout>();  
  34.         map = new HashMap<Integer, Integer>();  
  35.         for (int i = 0; i < columnCount; i++) {  
  36.             map.put(i, 0);  
  37.         }  
  38.         context = getContext();  
  39.         WindowManager windowManager = (WindowManager) context  
  40.                 .getSystemService(Context.WINDOW_SERVICE);  
  41.         display = windowManager.getDefaultDisplay();  
  42.         itemWidth = display.getWidth() / columnCount;// 根据屏幕大小计算每列大小  
  43.         for (int i = 0; i < columnCount; i++) {  
  44.             LinearLayout itemLayout = new LinearLayout(context);  
  45.             LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(  
  46.                     itemWidth, LayoutParams.WRAP_CONTENT);  
  47.             itemLayout.setPadding(1212);  
  48.             itemLayout.setOrientation(LinearLayout.VERTICAL);  
  49.             itemLayout.setLayoutParams(itemParam);  
  50.             waterfall_items.add(itemLayout);  
  51.             this.addView(itemLayout);  
  52.         }  
  53.     }  
  54.     /** 
  55.      * 贴图 
  56.      * @param article 文章实体 
  57.      * @param columnIndex 列索引 
  58.      */  
  59.     private void addImage(final Article article, int columnIndex) {  
  60.         ImageView item = (ImageView) LayoutInflater.from(context).inflate(  
  61.                 R.layout.waterfallitem, null);  
  62.         waterfall_items.get(columnIndex).addView(item);  
  63.         //int inSampleSize = 1;  
  64.         int h = 0;  
  65.         // int originalWidth = article.getWidth();  
  66.          int originalHieght = article.getHeight();  
  67.         //  
  68.         // int screenHeight = display.getHeight() / 7;  
  69.         // int screenWidth = display.getWidth() / 7;  
  70.         // float heightRatio = (float) Math.ceil(article.getHeight()  
  71.         // / screenHeight);  
  72.         // float widthRatio = (float) (Math.ceil(originalWidth / screenWidth));  
  73.         // if (heightRatio >= 1 && widthRatio >= 1) {  
  74.         // if (heightRatio > widthRatio) {  
  75.         // inSampleSize = (int) heightRatio;  
  76.         // } else {  
  77.         // inSampleSize = (int) widthRatio;  
  78.         // }  
  79.         // h = originalHieght;// inSampleSize;  
  80.         // } else {  
  81.         // h = originalHieght;  
  82.         // }  
  83.         h = originalHieght;  
  84.         int value = map.get(columnIndex);  
  85.         map.put(columnIndex, value+h);  
  86.           
  87.         TaskParam param = new TaskParam();  
  88.         param.setItemWidth(itemWidth);  
  89.         Bitmap defaultImage = BitmapFactory.decodeResource(getResources(),  
  90.                 R.drawable.loading);  
  91.         ImageLoaderTask task = new ImageLoaderTask(item, display,  
  92.                 article.getImage(), article, defaultImage, param);  
  93.         task.execute(param);  
  94.         item.setOnClickListener(new View.OnClickListener() {  
  95.             @Override  
  96.             public void onClick(View v) {  
  97.                 Intent intent = new Intent();  
  98.                 intent.setClassName(context.getPackageName(),  
  99.                         GirlDetailActivity.class.getName());  
  100.                 intent.putExtra("id", article.getId());  
  101.                 context.startActivity(intent);  
  102.             }  
  103.         });  
  104.           
  105.           
  106.     }  
  107.   
  108.     /** 
  109.      * 把图片集合填充到容器里 
  110.      * @param articles 
  111.      */  
  112.     public void setAdapter(List<Article> articles) {  
  113.         for (int i = 0; i < articles.size(); i++) {  
  114.             Article article = articles.get(i);  
  115.             addImage(article, getLowestColumn());  
  116.         }  
  117.     }  
  118.   
  119.     public int getLowestColumn(){  
  120.         List<Integer> list = new ArrayList<Integer>();  
  121.         list.addAll(map.values());  
  122.         Collections.sort(list);  
  123.         int min = list.get(0);  
  124.         Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();  
  125.         for (Map.Entry<Integer, Integer> entry : entrySet) {  
  126.             if(min==entry.getValue()){  
  127.                 return entry.getKey();  
  128.             }  
  129.         }  
  130.         return 0;  
  131.     }  
  132. }  

界面Activity:

[java] view plain copy
  1. Handler handler = new Handler() {  
  2.         public void handleMessage(android.os.Message msg) {  
  3.             waterfall_container.setAdapter(articles);//设置数据  
  4.                 if(countImage==currentCount){  
  5.                     System.out.println("已经到最后");  
  6.                     textView.setVisibility(View.VISIBLE);  
  7.                 }  
  8.         }  
  9.     };  
  10.   
  11.     @Override  
  12.     public void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);    
  15.         initLayout();  
  16.   
  17.     }  
  18.   
  19.     private void initLayout() {  
  20.           
  21.         textView = (TextView) findViewById(R.id.tv_tip);  
  22.         waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);  
  23.         waterfall_scroll.getView();  
  24.         waterfall_scroll.setOnScrollListener(new OnScrollListener() {  
  25.   
  26.             @Override  
  27.             public void onTop() {  
  28.                 Log.d("LazyScroll""Scroll to top");  
  29.             }  
  30.             @Override  
  31.             public void onScroll() {  
  32.                 Log.d("LazyScroll""Scroll");  
  33.             }  
  34.             @Override  
  35.             public void onBottom() {  
  36.                 // 滚动到最底端  
  37.                 if(countImage!=currentCount) {  
  38.                     new Thread(new LoadMyArticle()).start();//加载下一页  
  39.                 }  
  40.             }  
  41.         });  
  42.         waterfall_container = (MyLinearLayout) this  
  43.                 .findViewById(R.id.waterfall_container);  
  44.   
  45.         //初始化容器  
  46.         waterfall_container.initLayout(32222);  
  47.           
  48.         // 加载所有图片路径  
  49.         new Thread(new LoadMyArticle()).start();  
  50.   
  51.     }  
  52.   
  53.     public final class LoadMyArticle implements Runnable {  
  54.         @Override  
  55.         public void run() {  
  56.             try {  
  57.                 url_article_list.append("&page=").append(page++);  
  58.                 InputStream inputStream = GsonJsonParser  
  59.                         .getIputStream(url_article_list.toString());  
  60.                 ArticleJson articleJson = (ArticleJson) GsonJsonParser  
  61.                         .parseStreamToObject(inputStream, ArticleJson.class);  
  62.                 countImage = articleJson.getTotal();  
  63.                 articles = articleJson.getData();  
  64.                 currentCount += articles.size();  
  65.                 handler.sendEmptyMessage(1);  
  66.             } catch (IOException e) {  
  67.                 e.printStackTrace();  
  68.             }  
  69.         }  
  70.     }  

当点击某一张图片的时候,进入图片详情.这里使用了VIewPager来实现的.效果如下:

Android初级教程_图片混排效果和ViewPager的使用_第2张图片Android初级教程_图片混排效果和ViewPager的使用_第3张图片Android初级教程_图片混排效果和ViewPager的使用_第4张图片


实现如下:

[java] view plain copy
  1. private ViewPager viewPager;  
  2.     private List<ImageView> imageViews = new ArrayList<ImageView>();  
  3.     private List<Photo> photos;  
  4.     private Map<Integer,SoftReference<Bitmap>> cache = new HashMap<Integer,SoftReference<Bitmap>>();  
  5.     private ProgressBar pb;  
  6.     private MyAsyncTask myAsyncTask;  
  7.     int screenWidth ;  
  8.     int screenHeight;   
  9.     Handler handler = new Handler(){  
  10.         public void handleMessage(android.os.Message msg) {  
  11.             switch (msg.what) {  
  12.             case 1:  
  13.                 if(photos!=null&&photos.size()>0){  
  14.                     for (int i = 0; i < photos.size(); i++) {  
  15.                         ImageView imageView = new ImageView(GirlDetailActivity.this);  
  16.                         imageViews.add(imageView);  
  17.                     }  
  18.                     viewPager.setAdapter(new AwesomePagerAdapter());  
  19.                     myAsyncTask = new MyAsyncTask(0);  
  20.                     myAsyncTask.execute(photos.get(0).getImage());  
  21.                 }  
  22.                 break;  
  23.             }  
  24.         }  
  25.     };  
  26.     @Override  
  27.     protected void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  30.         setContentView(R.layout.girls_detail);  
  31.         Display display = getWindowManager().getDefaultDisplay();  
  32.         display = getWindowManager().getDefaultDisplay();  
  33.         screenWidth = display.getWidth();  
  34.         screenHeight = display.getHeight();  
  35.         init();  
  36.         Intent intent = getIntent();  
  37.         String id = intent.getStringExtra("id");  
  38.         StringBuffer url = new StringBuffer(url);  
  39.         url.append("?id=").append(id).append("&type=2");  
  40.         new Thread(new LoadImagePath(url.toString())).start();  
  41.   
  42.     }  
  43.   
  44.     public void init(){  
  45.           
  46.         pb = (ProgressBar) findViewById(R.id.widget);  
  47.           
  48.         viewPager = (ViewPager) findViewById(R.id.awesomepager);  
  49.           
  50.         viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {  
  51.             @Override  
  52.             public void onPageSelected(final int position) {  
  53.                 String image_path = photos.get(position).getImage();  
  54.                 pb.setVisibility(View.GONE);  
  55.                 if(cache.containsKey(position)){  
  56.                     Bitmap bitmap = cache.get(position).get();  
  57.                     if(bitmap!=null){  
  58.                         imageViews.get(position).setImageBitmap(bitmap);  
  59.                     }else {  
  60.                         if(!myAsyncTask.isCancelled()){  
  61.                             System.out.println("任务被取消");  
  62.                             myAsyncTask.cancel(true);  
  63.                         }  
  64.                         myAsyncTask = new MyAsyncTask(position);  
  65.                         myAsyncTask.execute(image_path);  
  66.                     }  
  67.                 }else {  
  68.                     if(!myAsyncTask.isCancelled()){  
  69.                         System.out.println("任务被取消");  
  70.                         myAsyncTask.cancel(true);  
  71.                     }  
  72.                     myAsyncTask = new MyAsyncTask(position);  
  73.                     myAsyncTask.execute(image_path);  
  74.                 }  
  75.             }  
  76.               
  77.             @Override  
  78.             public void onPageScrolled(int position, float positionOffset,  
  79.                     int positionOffsetPixels) {  
  80.                   
  81.             }  
  82.               
  83.             @Override  
  84.             public void onPageScrollStateChanged(int arg0) {  
  85.                   
  86.             }  
  87.         });  
  88.     }  
  89.   
  90.   
  91.   
  92.   
  93.     public class AwesomePagerAdapter extends PagerAdapter {  
  94.         @Override  
  95.         public int getCount() {  
  96.             return imageViews.size();  
  97.         }  
  98.   
  99.         @Override  
  100.         public Object instantiateItem(View collection, int position) {  
  101.   
  102.             ImageView imageView = imageViews.get(position);  
  103.             ((ViewPager) collection).addView(imageView, 0);  
  104.             return imageViews.get(position);  
  105.         }  
  106.   
  107.         @Override  
  108.         public void destroyItem(View collection, int position, Object view) {  
  109.             ((ViewPager) collection).removeView(imageViews.get(position));  
  110.         }  
  111.   
  112.         @Override  
  113.         public boolean isViewFromObject(View view, Object object) {  
  114.             // System.out.println("isViewFromObject");  
  115.             return view == (object);  
  116.         }  
  117.   
  118.         @Override  
  119.         public void finishUpdate(View arg0) {  
  120.             // System.out.println("finishUpdate");  
  121.         }  
  122.   
  123.         @Override  
  124.         public void restoreState(Parcelable arg0, ClassLoader arg1) {  
  125.             // System.out.println("restoreState");  
  126.         }  
  127.   
  128.         @Override  
  129.         public Parcelable saveState() {  
  130.             // System.out.println("saveState");  
  131.             return null;  
  132.         }  
  133.   
  134.         @Override  
  135.         public void startUpdate(View arg0) {  
  136.         }  
  137.   
  138.     }  
  139.   
  140.     @Override  
  141.     public void onStop() {  
  142.         super.onStop();  
  143.     }  
  144.   
  145.     @Override  
  146.     protected void onDestroy() {  
  147.         super.onDestroy();  
  148.     }  
  149.       
  150.     private final class LoadImagePath implements Runnable{  
  151.         private String url;  
  152.         public LoadImagePath(String url){  
  153.             this.url = url;  
  154.         }  
  155.         @Override  
  156.         public void run() {  
  157.             try {  
  158.                 InputStream in = JsonParse.getIputStream(url);  
  159.                 PhotoDetailJson photoDetailJson = (PhotoDetailJson) GsonJsonParser.parseStreamToObject(in, PhotoDetailJson.class);  
  160.                 PhotoDetail detail = photoDetailJson.getData();  
  161.                 photos = detail.getPhoto();  
  162.                 handler.sendEmptyMessage(1);  
  163.             } catch (IOException e) {  
  164.                 e.printStackTrace();  
  165.             }  
  166.         }  
  167.     }  
  168.       
  169.     public final class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{  
  170.   
  171.         private int position;  
  172.         public MyAsyncTask(int position){  
  173.             this.position = position;  
  174.         }  
  175.         @Override  
  176.         protected Bitmap doInBackground(String... params) {  
  177.             String path = params[0];  
  178.             try {  
  179.                 InputStream in = JsonParse.getIputStream(path);  
  180.                 //如果屏幕超过800*480  
  181.                 if(screenWidth>480&&screenHeight>800){//960x540  
  182.                     screenWidth = 480;  
  183.                     screenHeight = 800;  
  184.                 }  
  185.                  Bitmap bitmap = ImageUtil.getSizedBitmap(screenWidth, screenHeight, in);  
  186.                  cache.put(position, new SoftReference<Bitmap>(bitmap));  
  187.                  return bitmap;  
  188.             } catch (IOException e) {  
  189.                 e.printStackTrace();  
  190.             } catch (Exception e) {  
  191.                 e.printStackTrace();  
  192.             }  
  193.             return null;  
  194.         }  
  195.           
  196.         @Override  
  197.         protected void onPostExecute(Bitmap result) {  
  198.             super.onPostExecute(result);  
  199.             imageViews.get(position).setImageBitmap(result);  
  200.             pb.setVisibility(View.GONE);  
  201.         }  
  202.           
  203.         @Override  
  204.         protected void onPreExecute() {  
  205.             super.onPreExecute();  
  206.             pb.setVisibility(View.VISIBLE);  
  207.             imageViews.get(position).setImageResource(R.drawable.wait_girl_detail);  
  208.         }  
  209.           
  210.     }  

完毕!

欢迎转载,转载请注明出处:http://blog.csdn.net/johnny901114/article/details/7835139


谢谢大家.希望对你有帮助.有事请留言....


你可能感兴趣的:(Android初级教程_图片混排效果和ViewPager的使用)