如何更改 RecyclerView 中的列宽? (Android)

How to change column width in RecyclerView? (Android)

我有一个 RecyclerView 和一个 LinearLayoutManager。每行由一个 CheckBox 和两个 TextView 组成。

如何将每个 TextView 的宽度设置为其“列”的最大宽度,以便列左对齐?

在屏幕截图中,我希望第二个“列”中的 b 左对齐。

我试过以下方法:

   public void test(View view)
   {
      int max = 10;

      for (int i = 0; i < recyclerView.getLayoutManager().getChildCount(); i++)
      {
         View v = recyclerView.getLayoutManager().findViewByPosition(i);

         TextView tv1 = v.findViewById(R.id.textView1);

         if (tv1.getWidth() > max)
            max = tv1.getWidth();
      }

      for (int i = 0; i < recyclerView.getLayoutManager().getChildCount(); i++)
      {
         View v = recyclerView.getLayoutManager().findViewByPosition(i);

         TextView tv1 = v.findViewById(R.id.textView1);

         tv1.setWidth(max);
      }

这是行不通的,它的效果是“axxx”的宽度变小了,所以字母一个一个地画在另一个下面。第一个循环正确计算了最大宽度,但在第二个循环中分配宽度后,文本以某种方式折叠(因为 WRAP_CONTENT?)。

编辑:xml-文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_weight="1"
            android:text="CheckBox" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

我想让项目看起来像 table。

当您使用 textView.getWidth() 时,它通常会 return 0 值,这就是为什么您的最大值永远不会改变的原因。要获得 TextView 的实际宽度,您需要像这样使用 getMeasuredWidth()

textView1.measure(0,0);
if (textView1.getMeasuredWidth() > max) {
   max = textView1.getMeasuredWidth();
}

textView2.setWidth(max);

然后你得到这个:

但要小心。如果您的第一个 TextView 宽度太大,它可能会将您的第二个 TextView 推出布局。您需要检查设备宽度 and/or 将 maxWidth 设置为所需的值。我不知道您有多确定您的数据将来不会造成此问题。编码愉快!