Android中的瀑布流布局

本文介绍了一种自定义的RecyclerView及对应的Adapter实现方法,重点在于如何通过覆盖onScrollStateChanged方法来检测滚动到底部的行为,并提供了自定义的ImageView来展示圆角图片。

最近在布的局

自定义的recycleView:

public class RichRecyclerView extends RecyclerView {

    private View mLastHasFocusView;
    private long mKeyTime;

    public RichRecyclerView(Context context) {
        this(context, null);
    }

    public RichRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RichRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);
    }

    @Override
    public void onScrollStateChanged(int state) {
        if (state == RecyclerView.SCROLL_STATE_IDLE) {
            LayoutManager layoutManager = getLayoutManager();
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                StaggeredGridLayoutManager lm = (StaggeredGridLayoutManager) layoutManager;
                int columnCount = lm.getColumnCountForAccessibility(null, null);
                int positions[] = new int[columnCount];
                lm.findLastVisibleItemPositions(positions);
                for (int i = 0; i < positions.length; i++) {
//                    System.out.println("当前视图上的最后可见列的位置" + positions[i]);
                }
                for (int i = 0; i < positions.length; i++) {
                    /**
                     * 判断lastItem的底边到recyclerView顶部的距离
                     * 是否小于recyclerView的高度
                     * 如果小于或等于 说明滚动到了底部
                     */
                    if (positions[i] >= lm.getItemCount() - columnCount) {
                        System.out.println("滑动到底了1");

                        System.out.println("总adapter的条目数:" + lm.getItemCount()); //内部取的adapter的方法
                        System.out.println("总的列数:" + columnCount);
                        System.out.println("符号条件的最后可见列上的position" + positions[i]);

                        ViewGroup.LayoutParams layoutParams = lm.findViewByPosition(positions[i]).getLayoutParams();
                        layoutParams.height = lm.findViewByPosition(positions[i]).getHeight() +
                                getHeight() - lm.findViewByPosition(positions[i]).getBottom();
                        lm.findViewByPosition(positions[i]).setLayoutParams(layoutParams);
                    }
                }
                int[] into = new int[columnCount];
                lm.findFirstCompletelyVisibleItemPositions(into);
                for (int i = 0; i < into.length; i++) {
                    System.out.println("首次完全可见的view位置:" + into[i]);
                }

                lm.findFirstVisibleItemPositions(into);
                for (int i = 0; i < into.length; i++) {
                    System.out.println("首次可见的view位置(即使部份可见):" + into[i]);
                }

            } else if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager lm = (LinearLayoutManager) layoutManager;
                int position = lm.findLastVisibleItemPosition();
                if (position + 1 == lm.getItemCount()) {
                    System.out.println("滑动到底了2");

                }
            }
        }
        super.onScrollStateChanged(state);
    }
   /* @Override
    public void onScrollStateChanged(int state) {
        // 如果停止滑动
        if (state == SCROLL_STATE_IDLE) {
            LayoutManager layoutManager = getLayoutManager();
            if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
                // 获取布局管理器
                StaggeredGridLayoutManager layout =
                        (StaggeredGridLayoutManager) layoutManager;
                // 用来记录lastItem的position
                // 由于瀑布流有多个列 所以此处用数组存储
                int column = layout.getColumnCountForAccessibility(null, null);
                int positions[] = new int[column];
                // 获取lastItem的positions
                layout.findLastVisibleItemPositions(positions);
                for (int i = 0; i < positions.length; i++) {
                    *//**
     * 判断lastItem的底边到recyclerView顶部的距离
     * 是否小于recyclerView的高度
     * 如果小于或等于 说明滚动到了底部
     *//*
                    // 刚才忘了写判断是否是最后一个item了
                    if (positions[i] >= (layout.getItemCount() - column)
                            && layout.findViewByPosition(positions[i]).getBottom() <= getHeight()) {
                        *//**
     * 此处实现你的业务逻辑
     *//*
                        Log.e("到底了", "true");
                        break;
                    }

                }
            } else if (getLayoutManager() instanceof LinearLayoutManager) {

                LinearLayoutManager layout =
                        (LinearLayoutManager) layoutManager;
                int position = layout.findLastVisibleItemPosition();
                // 刚才忘了写判断是否是最后一个item了
                if (position - 1 == layout.getItemCount()
                        && layout.findViewByPosition(position).getBottom() <= getHeight()) {
                    Log.e("到底了", "true");
                }

            }

        }
        super.onScrollStateChanged(state);
    }*/
}


自定义的Adapter:

public class MasonryAdapter extends RecyclerView.Adapter<MasonryAdapter.MasonryView> {
    private static Context context;
    private ArrayList<Integer> datas;
    private SplashActivity.MyOnItemClickListener myOnItemClickListener;
    private static RecycleItemClickListener itemClickListener;
    private float width;

    public MasonryAdapter(Context context, ArrayList<Integer> datas, SplashActivity.MyOnItemClickListener myOnItemClickListener, float width) {

        this.context = context;
        this.datas = datas;
        this.myOnItemClickListener = myOnItemClickListener;
        this.width = width;
    }

    @Override
    public MasonryView onCreateViewHolder(ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.imageview, viewGroup, false);
        return new MasonryView(view);
    }

    @Override
    public void onBindViewHolder(MasonryView masonryView, int position) {


        masonryView.imageView.setImageResource(datas.get(position));

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), datas.get(position));
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        float scale = width / bitmapWidth;
        float height = bitmapHeight * scale;

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int) width, (int) height);
        masonryView.imageView.setLayoutParams(layoutParams);
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    //viewHolder
    public static class MasonryView extends RecyclerView.ViewHolder implements View.OnClickListener {

        private XCRoundRectImageView imageView;


        @Override
        public void onClick(View v) {
           // itemClickListener.onItemClick(v, this.getLayoutPosition());
            Toast.makeText(context,"我被戳了",Toast.LENGTH_SHORT).show();
        }

        public MasonryView(View itemView) {
            super(itemView);
            imageView = (XCRoundRectImageView) itemView.findViewById(R.id.image);
            itemView.setOnClickListener(this);
        }
    }
}

自定义的ImageView:

public class XCRoundRectImageView extends ImageView {
    private Paint paint;

    public XCRoundRectImageView(Context context) {
        this(context,null);
    }

    public XCRoundRectImageView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public XCRoundRectImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        paint  = new Paint();
    }

    /**
     * 绘制圆角矩形图片
     * @author caizhiming
     */
    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();
        if (null != drawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            Bitmap b = getRoundBitmap(bitmap, 10);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
            paint.reset();
            canvas.drawBitmap(b, rectSrc, rectDest, paint);

        } else {
            super.onDraw(canvas);
        }
    }

    /**
     * 获取圆角矩形图片方法
     * @param bitmap
     * @param roundPx,一般设置成14
     * @return Bitmap
     * @author caizhiming
     */
    private Bitmap getRoundBitmap(Bitmap bitmap, int roundPx) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;

        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        int x = bitmap.getWidth();

        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;


    }
}

布局:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"
        android:orientation="vertical">

        <com.bruin.zheng.pinterestdemo.view.XCRoundRectImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/m_11k1_x_0_v3_04_thumb" />

        <!--  <android.support.v7.widget.RecyclerView
              android:id="@+id/recycler"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingLeft="10dp"
              android:paddingRight="10dp" />-->

        <com.bruin.zheng.pinterestdemo.view.RichRecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp"
            android:paddingRight="10dp" />

        <com.bruin.zheng.pinterestdemo.view.XCRoundRectImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/m_11k1_x_0_v3_04_thumb" />
    </LinearLayout>
</ScrollView>
item的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <FrameLayout
        android:id="@+id/relativelayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp">


      <!--  <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitXY" />-->
        <com.bruin.zheng.pinterestdemo.view.XCRoundRectImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitXY" />
    </FrameLayout>
</RelativeLayout>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值