今天研究了一下瀑布流,来说一下我实现它的方法。
看一下效果图:
基本的思路是重写了 ScrollView,让它包含一个LinearLayout,然后你要实现几列的就在里面添加几个LinearLayout,然后在循环在那几个LinearLayout里添加图片(也可以是别的view等)。
想看看重写ScrollView的LazyScrollView类
在LazyScrollView类中定义了滑动的接口
/** * 定义接口 * * @author lilongchun_hz * */ public interface OnScrollListener { void onBottom(); void onTop(); void onScroller(); } private OnScrollListener onScrollListener; public void setOnScrollListener(OnScrollListener onScrollListener) { this.onScrollListener = onScrollListener; }
然后在类中实现onTouchListener,在onTouchListener中实现滑动时,调用OnScrollListener
// 屏幕touch点击事件 OnTouchListener onTouchListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: System.out.println("down"); break; case MotionEvent.ACTION_UP: System.out.println("up"); if(view != null && onScrollListener !=null){ handler.sendMessageDelayed(handler.obtainMessage(1), 200); } break; default: break; } return false; } };
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: // 滑动到底部 if (view.getMeasuredHeight() <= (getScrollY() + getMeasuredHeight())) { if (onScrollListener != null) { onScrollListener.onBottom(); } } else if (getScrollY() == 0) { // 滑动到顶部 if (onScrollListener != null) { onScrollListener.onTop(); } } else {// 滑动中 if (onScrollListener != null) { onScrollListener.onScroller(); } } break; default: break; } } };
然后就是在MainActivity中添加LinearLayout
for (int i = 0; i < COLUMN_COUNT; i++) { // 生成三列的LinearLayout LinearLayout itemLayout = new LinearLayout(this); LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams( itemWidth, LayoutParams.WRAP_CONTENT); itemLayout.setPadding(2, 2, 2, 2); itemLayout.setOrientation(LinearLayout.VERTICAL); itemLayout.setLayoutParams(itemParam); waterfall_items.add(itemLayout); waterfall_container.addView(itemLayout); }
其余的就是添加ImageView了,这块就不讲了,其实都差不多。有需要的朋友可以下载源码看。