Android GridLayoutManager一行只有一个背景图
创始人
2024-08-14 03:00:18
0

要实现Android GridLayoutManager中一行只有一个背景图,可以通过自定义RecyclerView的ItemDecoration来实现。以下是示例代码:

  1. 创建一个名为SingleBackgroundItemDecoration的自定义ItemDecoration类:
public class SingleBackgroundItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable background;

    public SingleBackgroundItemDecoration(Context context, @DrawableRes int backgroundResId) {
        background = ContextCompat.getDrawable(context, backgroundResId);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
        if (position % spanCount == 0) {
            outRect.left = 0;
            outRect.right = parent.getWidth() - parent.getPaddingRight();
        } else {
            outRect.left = parent.getWidth();
            outRect.right = 0;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(child);
            if (position % spanCount == 0) {
                background.setBounds(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
                background.draw(c);
            }
        }
    }
}
  1. 在你的Activity或Fragment中,找到你的RecyclerView,并在设置LayoutManager后添加ItemDecoration:
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount));
recyclerView.addItemDecoration(new SingleBackgroundItemDecoration(this, R.drawable.background));

在这个示例中,我们假设你的背景图资源文件为background,你可以根据自己的需求修改背景图的资源和布局逻辑。

相关内容

热门资讯

让我来分享经验!德普辅助软件,... 让我来分享经验!德普辅助软件,wepoker黑侠辅助器正版下载,揭秘攻略(有挂攻略);1分钟了解详细...
透视透视"aapok... 《透视透视"aapoker怎么控制牌"详细辅助分享教程(都是有挂)》 aapoker怎么控制牌软件透...
科技分享!德普之星有透视辅助吗... 《科技分享!德普之星有透视辅助吗,wpk辅助软件,切实教程(有挂教程)》 德普之星有透视辅助吗软件透...
辅助透视"wepok... 辅助透视"wepoker辅助透视软件"详细辅助德州论坛(切实有挂);wepoker辅助透视软件软件透...
一分钟教你!wepoker私人... 一分钟教你!wepoker私人局辅助挂,来玩app 德州 辅助,曝光教程(有挂攻略);wepoker...
透视辅助"wepok... 1、透视辅助"wepoker可以透视码"详细辅助德州论坛(从来真的是有挂)(UU poker、wep...
盘点一款!安装不了wepoke... 此外,数据分析德州(wepoker插件程序激活码)辅助神器app还具备辅助透视行为开挂功能,通过对客...
透视黑科技"购买we... 《透视黑科技"购买wepoker模拟器"详细辅助规律教程(素来是有挂)》 购买wepoker模拟器软...
推荐一款!hhpkoer辅助器... 推荐一款!hhpkoer辅助器视频,wepoker破解版内购,AI教程(有挂技巧);致您一封信;亲爱...
透视总结"wepok... 透视总结"wepoker透视脚本视频"详细辅助力荐教程(原生存在有挂);建议优先通过wepoker透...