android 瀑布流原理及实例

最近发现瀑布流这个展现形式很是热门,于是就研究着看看,结果发现瀑布流其实也很简单,并不是那么复杂。先看代码,然后再解释

先看图

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/layout01"
                android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" >
        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout02"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" >
        </LinearLayout>
    </LinearLayout>

</ScrollView>

这里大家看的很清楚,就一个ScrollView和2个LinearLayout,最外面的那层linearlayout不用去管他。想必大家也明白了,这次我要做的瀑布流是只有2列。ScrollView的作用其实就是让这个瀑布具有滚动的作用!

下面来看代码

代码没什么难度,我就不解释了。大家自己看吧,我传上完整的实例代码

package com.pb.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class TestPbActivity extends Activity
{
    /** Called when the activity is first created. */
    private LinearLayout layout01;
    private LinearLayout layout02;
    private Drawable[] drawables;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        layout01 = (LinearLayout) findViewById(R.id.layout01);
        layout02 = (LinearLayout) findViewById(R.id.layout02);
        String[] imagePathStr = { "http://www.cf69.com/Upfiles/BeyondPic/2010-08/20108175740983313.jpg",
                "http://www.syfff.com/UploadFile/pic/2008122163204.jpg", "http://pic.newssc.org/0/10/34/32/10343297_564251.jpg",
                "http://ent.hangzhou.com.cn/images/20090311/zym2009031323.jpg", "http://a4.att.hudong.com/86/60/01300000013093119087608457965.jpg",
                "http://file.sdteacher.gov.cn/upload/gz0901/images/0907/22/110437191.jpg",
                "http://www.fun9.cn/uploadfile/starpic/uploadpics/200910/20091008090155126.jpg",
                "http://img3.yxlady.com/yl/UploadFiles_5361/20110820/20110820120609469.jpg",
                "http://news.sznews.com/content/images/site3/20070827/001558d90baa083c6da20d.jpg", "http://henan.sinaimg.cn/cr/2010/0824/2297073692.jpg",
                "http://www.cf69.com/Upfiles/BeyondPic/2010-08/20108175740983313.jpg", "http://www.syfff.com/UploadFile/pic/2008122163204.jpg",
                "http://pic.newssc.org/0/10/34/32/10343297_564251.jpg", "http://ent.hangzhou.com.cn/images/20090311/zym2009031323.jpg",
                "http://a4.att.hudong.com/86/60/01300000013093119087608457965.jpg", "http://file.sdteacher.gov.cn/upload/gz0901/images/0907/22/110437191.jpg",
                "http://www.fun9.cn/uploadfile/starpic/uploadpics/200910/20091008090155126.jpg",
                "http://img3.yxlady.com/yl/UploadFiles_5361/20110820/20110820120609469.jpg",
                "http://news.sznews.com/content/images/site3/20070827/001558d90baa083c6da20d.jpg", "http://henan.sinaimg.cn/cr/2010/0824/2297073692.jpg" };
        // new LoadImageViews().execute(imagePathStr);
        int j = 0;
        for (int i = 0; i < imagePathStr.length; i++)
        {
            addBitMapToImage(imagePathStr[i], j, i);
            j++;
            if (j >= 2)
            {
                j = 0;
            }
        }
    }
    // 添加imageview 到layout
    public void addBitMapToImage(String imagePath, int j, int i)
    {
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        new ImageDownLoadAsyncTask(this,imagePath, imageView).execute((Void)null);
        imageView.setTag(i);
        if (j == 0)
        {
            layout01.addView(imageView);
        } else if (j == 1)
        {
            layout02.addView(imageView);
        }
        imageView.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                Toast.makeText(TestPbActivity.this, "您点击了" + v.getTag() + "个Item", Toast.LENGTH_SHORT).show();

            }
        });
    }
}
/**
 * 异步下载图片
 * 
 * @author sy
 * 
 */
public class ImageDownLoadAsyncTask extends AsyncTask<Void, Void, Drawable>
{
    private String imagePath;
    private View imageView;
    private static final String ALBUM_PATH = "/sdcard/pb";
    ProgressDialog progressDialog;
    private Context context;

    /**
     * 构造方法
     * 
     * @param context
     * @param imagePath
     * @param imageView
     */
    public ImageDownLoadAsyncTask(Context context, String imagePath, View imageView)
    {
        this.imagePath = imagePath;
        this.imageView = imageView;
        this.context = context;
    }

    @Override
    protected Drawable doInBackground(Void... params)
    {
        // TODO Auto-generated method stub
        String filePath = ALBUM_PATH + imagePath.substring(imagePath.lastIndexOf("/"));
        File mfile = new File(filePath);
        if (mfile.exists())
        {// 若该文件存在
            Bitmap bm = BitmapFactory.decodeFile(filePath);
            BitmapDrawable bd = new BitmapDrawable(bm);
            return bd;
        } else
        {
            URL url;
            try
            {
                url = new URL(imagePath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                BitmapDrawable bd = new BitmapDrawable(bitmap);
                saveFile(bd, imagePath.substring(imagePath.lastIndexOf("/")));
                return bd;
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Drawable drawable)
    {
        // TODO Auto-generated method stub
        super.onPostExecute(drawable);
        if (drawable != null)
        {
            imageView.setBackgroundDrawable(drawable);
        }
        progressDialog.dismiss();
    }

    @Override
    protected void onPreExecute()
    {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = ProgressDialog.show(context, "", "正在下载图片,请售后");
    }

    /**
     * 将图片存入SD卡
     * 
     * @param drawable
     * @param fileName
     * @throws IOException
     * @author sy
     */
    public void saveFile(Drawable drawable, String fileName) throws IOException
    {

        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists())
        {
            dirFile.mkdirs();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bm = bd.getBitmap();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

}

哎,不知道博客园怎么上传附近。。纠结。

原文地址:https://www.cnblogs.com/sy171822716/p/2626836.html