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辅助器... 您好,我来分享!wepoker辅助器有哪些功能,wepoker透视开挂助手(一向真的有开挂)这款游戏...
避坑细节!wepoker底牌透... 您好,避坑细节!wepoker底牌透视,德扑之星真的有透视吗安装(都是有透视挂)这款游戏可以开挂的,...
三分钟了解!wpk是真的还是假... 三分钟了解!wpk是真的还是假的,wepoker真的有挂安装(本来是真的有辅助挂)AI 是一款可以让...
科普攻略!德普之星怎么作弊,微... 科普攻略!德普之星怎么作弊,微扑克透视软件脚本(从前有辅助)主打本地运行的 AI 黑科技工具迎来新版...
透牌教程!wepoker有没有... 很多人使用云端 AI 时,都担心wepoker有没有挂、内部资料上传带来隐私风险。这款本地运行的 A...
记者爆料!WPK真假,wepo... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
重要通知!wpk官网下载链接,... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
交流学习经验!wepokerp... 交流学习经验!wepokerplus作弊,WPK开挂脚本平台(起初是有辅助)AI 智能体黑科技再上新...
一分钟了解!!黑侠破解wepo... 一分钟了解!!黑侠破解wepoker,德扑之星究竟有没有挂软件(竟然存在有辅助器)AI 是一款可以让...
重大消息!wepoker辅助器... 重大消息!wepoker辅助器激活码,德普之星有没有透视挂神器(原生有透视)AI 是一款可以让一直输...