首页 > 解决方案 > 通过最宽的子视图和 match_parent 第二个子视图拉伸布局

问题描述

我需要按最宽的子视图拉伸布局,并按父宽度匹配第二个视图。换句话说,结合 wrap_content 和 match_parent。

这是示例 XML(回收站视图中的项目):

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

    <TextView
      android:id="@+id/first"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@android:color/holo_blue_dark"
      android:text="Loooong"/>

    <TextView
      android:id="@+id/second"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@android:color/holo_red_light"
      android:text="Short"/>

</LinearLayout>

例子

我试图在 onMeasure() 方法中将 match_parent 设置为第二个视图,如果它的宽度小于第一个视图,但是当我滚动 recycler_view 时,一些视图被重置回 wrap_content。

我怎样才能实现这种行为?也许约束布局可以提供帮助?

标签: androidandroid-layout

解决方案


为什么不将两者都设置为match_parent

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

    <TextView
        android:id="@+id/first"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_dark"
        android:text="Loooong"/>

    <TextView
        android:id="@+id/second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_light"
        android:text="Short"/>

</LinearLayout>

你不需要onMeasure()


推荐阅读