【问题标题】:Can I set dynamic column widths in GridManagerLayout in Android?我可以在 Android 的 GridManagerLayout 中设置动态列宽吗?
【发布时间】:2016-09-24 07:03:37
【问题描述】:

我有一个recyclerView 和一个gridManagerLayout,如下所示:

GridLayoutManager manager = new GridLayoutManager(Main.this, 10);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);

有没有办法为每列设置不同的宽度?我正在尝试实现这样的目标:

如您所见,第 0、2、4、6 和 8 列需要小于其他列。

我尝试过manager.setSpanSizeLookup(spanSizeLookup),但我不想更改layout managerspanCount

这就是我现在拥有的

我通过调用在构造函数中设置每个支架的宽度 itemView.getLayoutParams().width = THE_WIDTH;

好像黄线在他们的位置,不知道为什么其他人有偏移

这是图像的 XML

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

<ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:adjustViewBounds="true"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/text"
    android:scaleType="centerCrop"/>

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Category name"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:background="#7f007f"/>

</RelativeLayout>

这是它们之间空间的xml

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="25dp"
android:layout_height="match_parent"
android:background="#ffff00"/>

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    在您的适配器中,使用 layout.params 动态设置项目的宽度,例如。

    tv.setLayoutParams(new ViewGroup.LayoutParams(
    10,
    ViewGroup.LayoutParams.WRAP_CONTENT));
    

    检查,

    if(position%2==0) {
    your_item_parent_layout.setLayoutParams(new ViewGroup.LayoutParams(
    10,
    ViewGroup.LayoutParams.WRAP_CONTENT));
    }
    else{
    your_item_parent_layout.setLayoutParams(new ViewGroup.LayoutParams(
    100,
    ViewGroup.LayoutParams.WRAP_CONTENT));
    }
    

    在您的适配器中。

    希望对你有帮助。

    【讨论】:

    • 上传你的两个xml文件
    【解决方案2】:

    为此,您需要使用AdaptergetItemViewType 方法,并且您必须发送布局类型,在onCreateViewHolder 中,您需要根据您的类型发送inflate layouts。并且您可以将widthheight 设置为您的两个不同的layouts,如屏幕截图所示

    【讨论】:

    • 我已经在每个持有者的构造函数中这样做了,根据它的类型。
    • @kimv 那么问题出在哪里?它应该工作得很好
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2017-01-31
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多