Android初級教程_圖片混排效果和ViewPager的使用

前段時間公司需要實現圖片混排的效果,類似"美麗說"那樣,寬度一樣,高度不一.總共有3列.每次加載更多的時候都是往最低的那列添加圖片,這樣就不會出現有的列非常多的圖片,而有的列圖片很少,效果如下圖所示:

 

當滑倒底部的時候如果還有圖片則自動加載下一頁.
代碼實現如下:
首先自定義佈局:
[java]
public class MyLinearLayout extends LinearLayout { 
 
    private Map<Integer, Integer> map; 
    private ArrayList<LinearLayout> waterfall_items; 
    private Context context; 
    private Display display; 
    private int itemWidth; 
 
    public MyLinearLayout(Context context, AttributeSet attrs) { 
        super(context, attrs); 
    } 
    public MyLinearLayout(Context context) { 
        super(context); 
    } 
 
    /**
     * 初始化容器 
     * @param columnCount
     *            列數
     * @param paddingLeft
     * @param paddingTop
     * @param paddingRight
     * @param paddingBottom
     */ 
    public void initLayout(int columnCount, int paddingLeft, int paddingTop, 
            int paddingRight, int paddingBottom) { 
         
        if (columnCount < 1) 
            columnCount = 3; 
         
        Constans.COLUMN_COUNT = columnCount; 
         
        waterfall_items = new ArrayList<LinearLayout>(); 
        map = new HashMap<Integer, Integer>(); 
        for (int i = 0; i < columnCount; i++) { 
            map.put(i, 0); 
        } 
        context = getContext(); 
        WindowManager windowManager = (WindowManager) context 
                .getSystemService(Context.WINDOW_SERVICE); 
        display = windowManager.getDefaultDisplay(); 
        itemWidth = display.getWidth() / columnCount;// 根據屏幕大小計算每列大小 
        for (int i = 0; i < columnCount; i++) { 
            LinearLayout itemLayout = new LinearLayout(context); 
            LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams( 
                    itemWidth, LayoutParams.WRAP_CONTENT); 
            itemLayout.setPadding(1, 2, 1, 2); 
            itemLayout.setOrientation(LinearLayout.VERTICAL); 
            itemLayout.setLayoutParams(itemParam); 
            waterfall_items.add(itemLayout); 
            this.addView(itemLayout); 
        } 
    } 
    /**
     * 貼圖
     * @param article 文章實體
     * @param columnIndex 列索引
     */ 
    private void addImage(final Article article, int columnIndex) { 
        ImageView item = (ImageView) LayoutInflater.from(context).inflate( 
                R.layout.waterfallitem, null); 
        waterfall_items.get(columnIndex).addView(item); 
        //int inSampleSize = 1; 
        int h = 0; 
        // int originalWidth = article.getWidth(); 
         int originalHieght = article.getHeight(); 
        // 
        // int screenHeight = display.getHeight() / 7; 
        // int screenWidth = display.getWidth() / 7; 
        // float heightRatio = (float) Math.ceil(article.getHeight() 
        // / screenHeight); 
        // float widthRatio = (float) (Math.ceil(originalWidth / screenWidth)); 
        // if (heightRatio >= 1 && widthRatio >= 1) { 
        // if (heightRatio > widthRatio) { 
        // inSampleSize = (int) heightRatio; 
        // } else { 
        // inSampleSize = (int) widthRatio; 
        // } 
        // h = originalHieght;// inSampleSize; 
        // } else { 
        // h = originalHieght; 
        // } 
        h = originalHieght; 
        int value = map.get(columnIndex); 
        map.put(columnIndex, value+h); 
         
        TaskParam param = new TaskParam(); 
        param.setItemWidth(itemWidth); 
        Bitmap defaultImage = BitmapFactory.decodeResource(getResources(), 
                R.drawable.loading); 
        ImageLoaderTask task = new ImageLoaderTask(item, display, 
                article.getImage(), article, defaultImage, param); 
        task.execute(param); 
        item.setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                Intent intent = new Intent(); 
                intent.setClassName(context.getPackageName(), 
                        GirlDetailActivity.class.getName()); 
                intent.putExtra("id", article.getId()); 
                context.startActivity(intent); 
            } 
        }); 
         
         
    } 
 
    /**
     * 把圖片集合填充到容器裡
     * @param articles
     */ 
    public void setAdapter(List<Article> articles) { 
        for (int i = 0; i < articles.size(); i++) { 
            Article article = articles.get(i); 
            addImage(article, getLowestColumn()); 
        } 
    } 
 
    public int getLowestColumn(){ 
        List<Integer> list = new ArrayList<Integer>(); 
        list.addAll(map.values()); 
        Collections.sort(list); 
        int min = list.get(0); 
        Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet(); 
        for (Map.Entry<Integer, Integer> entry : entrySet) { 
            if(min==entry.getValue()){ 
                return entry.getKey(); 
            } 
        } 
        return 0; 
    } 

界面Activity:
[java] 
Handler handler = new Handler() { 
        public void handleMessage(android.os.Message msg) { 
            waterfall_container.setAdapter(articles);//設置數據 
                if(countImage==currentCount){ 
                    System.out.println("已經到最後"); 
                    textView.setVisibility(View.VISIBLE); 
                } 
        } 
    }; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);   
        initLayout(); 
 
    } 
 
    private void initLayout() { 
         
        textView = (TextView) findViewById(R.id.tv_tip); 
        waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll); 
        waterfall_scroll.getView(); 
        waterfall_scroll.setOnScrollListener(new OnScrollListener() { 
 
            @Override 
            public void onTop() { 
                Log.d("LazyScroll", "Scroll to top"); 
            } 
            @Override 
            public void onScroll() { 
                Log.d("LazyScroll", "Scroll"); 
            } 
            @Override 
            public void onBottom() { 
                // 滾動到最底端 
                if(countImage!=currentCount) { 
                    new Thread(new LoadMyArticle()).start();//加載下一頁 
                } 
            } 
        }); 
        waterfall_container = (MyLinearLayout) this 
                .findViewById(R.id.waterfall_container); 
 
        //初始化容器 
        waterfall_container.initLayout(3, 2, 2, 2, 2); 
         
        // 加載所有圖片路徑 
        new Thread(new LoadMyArticle()).start(); 
 
    } 
 
    public final class LoadMyArticle implements Runnable { 
        @Override 
        public void run() { 
            try { 
                url_article_list.append("&page=").append(page++); 
                InputStream inputStream = GsonJsonParser 
                        .getIputStream(url_article_list.toString()); 
                ArticleJson articleJson = (ArticleJson) GsonJsonParser 
                        .parseStreamToObject(inputStream, ArticleJson.class); 
                countImage = articleJson.getTotal(); 
                articles = articleJson.getData(); 
                currentCount += articles.size(); 
                handler.sendEmptyMessage(1); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

當點擊某一張圖片的時候,進入圖片詳情.這裡使用瞭VIewPager來實現的.效果如下:



實現如下:
[java] 
private ViewPager viewPager; 
    private List<ImageView> imageViews = new ArrayList<ImageView>(); 
    private List<Photo> photos; 
    private Map<Integer,SoftReference<Bitmap>> cache = new HashMap<Integer,SoftReference<Bitmap>>(); 
    private ProgressBar pb; 
    private MyAsyncTask myAsyncTask; 
    int screenWidth ; 
    int screenHeight;  
    Handler handler = new Handler(){ 
        public void handleMessage(android.os.Message msg) { 
            switch (msg.what) { 
            case 1: 
                if(photos!=null&&photos.size()>0){ 
                    for (int i = 0; i < photos.size(); i++) { 
                        ImageView imageView = new ImageView(GirlDetailActivity.this); 
                        imageViews.add(imageView); 
                    } 
                    viewPager.setAdapter(new AwesomePagerAdapter()); 
                    myAsyncTask = new MyAsyncTask(0); 
                    myAsyncTask.execute(photos.get(0).getImage()); 
                } 
                break; 
            } 
        } 
    }; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.girls_detail); 
        Display display = getWindowManager().getDefaultDisplay(); 
        display = getWindowManager().getDefaultDisplay(); 
        screenWidth = display.getWidth(); 
        screenHeight = display.getHeight(); 
        init(); 
        Intent intent = getIntent(); 
        String id = intent.getStringExtra("id"); 
        StringBuffer url = new StringBuffer(url); 
        url.append("?id=").append(id).append("&type=2"); 
        new Thread(new LoadImagePath(url.toString())).start(); 
 
    } 
 
    public void init(){ 
         
        pb = (ProgressBar) findViewById(R.id.widget); 
         
        viewPager = (ViewPager) findViewById(R.id.awesomepager); 
         
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
            @Override 
            public void onPageSelected(final int position) { 
                String image_path = photos.get(position).getImage(); 
                pb.setVisibility(View.GONE); 
                if(cache.containsKey(position)){ 
                    Bitmap bitmap = cache.get(position).get(); 
                    if(bitmap!=null){ 
                        imageViews.get(position).setImageBitmap(bitmap); 
                    }else { 
                        if(!myAsyncTask.isCancelled()){ 
                            System.out.println("任務被取消"); 
                            myAsyncTask.cancel(true); 
                        } 
                        myAsyncTask = new MyAsyncTask(position); 
                        myAsyncTask.execute(image_path); 
                    } 
                }else { 
                    if(!myAsyncTask.isCancelled()){ 
                        System.out.println("任務被取消"); 
                        myAsyncTask.cancel(true); 
                    } 
                    myAsyncTask = new MyAsyncTask(position); 
                    myAsyncTask.execute(image_path); 
                } 
            } 
             
            @Override 
            public void onPageScrolled(int position, float positionOffset, 
                    int positionOffsetPixels) { 
                 
            } 
             
            @Override 
            public void onPageScrollStateChanged(int arg0) { 
                 
            } 
        }); 
    } 
 
 
 
 
    public class AwesomePagerAdapter extends PagerAdapter { 
        @Override 
        public int getCount() { 
            return imageViews.size(); 
        } 
 
        @Override 
        public Object instantiateItem(View collection, int position) { 
 
            ImageView imageView = imageViews.get(position); 
            ((ViewPager) collection).addView(imageView, 0); 
            return imageViews.get(position); 
        } 
 
        @Override 
        public void destroyItem(View collection, int position, Object view) { 
            ((ViewPager) collection).removeView(imageViews.get(position)); 
        } 
 
        @Override 
        public boolean isViewFromObject(View view, Object object) { 
            // System.out.println("isViewFromObject"); 
            return view == (object); 
        } 
 
        @Override 
        public void finishUpdate(View arg0) { 
            // System.out.println("finishUpdate"); 
        } 
 
        @Override 
        public void restoreState(Parcelable arg0, ClassLoader arg1) { 
            // System.out.println("restoreState"); 
        } 
 
        @Override 
        public Parcelable saveState() { 
            // System.out.println("saveState"); 
            return null; 
        } 
 
        @Override 
        public void startUpdate(View arg0) { 
        } 
 
    } 
 
    @Override 
    public void onStop() { 
        super.onStop(); 
    } 
 
    @Override 
    protected void onDestroy() { 
        super.onDestroy(); 
    } 
     
    private final class LoadImagePath implements Runnable{ 
        private String url; 
        public LoadImagePath(String url){ 
            this.url = url; 
        } 
        @Override 
        public void run() { 
            try { 
                InputStream in = JsonParse.getIputStream(url); 
                PhotoDetailJson photoDetailJson = (PhotoDetailJson) GsonJsonParser.parseStreamToObject(in, PhotoDetailJson.class); 
                PhotoDetail detail = photoDetailJson.getData(); 
                photos = detail.getPhoto(); 
                handler.sendEmptyMessage(1); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public final class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{ 
 
        private int position; 
        public MyAsyncTask(int position){ 
            this.position = position; 
        } 
        @Override 
        protected Bitmap doInBackground(String… params) { 
            String path = params[0]; 
            try { 
                InputStream in = JsonParse.getIputStream(path); 
                //如果屏幕超過800*480 
                if(screenWidth>480&&screenHeight>800){//960×540 
                    screenWidth = 480; 
                    screenHeight = 800; 
                } 
                 Bitmap bitmap = ImageUtil.getSizedBitmap(screenWidth, screenHeight, in); 
                 cache.put(position, new SoftReference<Bitmap>(bitmap)); 
                 return bitmap; 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
            return null; 
        } 
         
        @Override 
        protected void onPostExecute(Bitmap result) { 
            super.onPostExecute(result); 
            imageViews.get(position).setImageBitmap(result); 
            pb.setVisibility(View.GONE); 
        } 
         
        @Override 
        protected void onPreExecute() { 
            super.onPreExecute(); 
            pb.setVisibility(View.VISIBLE); 
            imageViews.get(position).setImageResource(R.drawable.wait_girl_detail); 
        } 
         
    } 

作者:johnny901114

發佈留言