【发布时间】:2022-11-11 07:36:35
【问题描述】:
我有一个 RecyclerView,其条目是 CardViews。每个 CardView 都包含一个带有 5 个 TextView 的水平 LinearLayout。无论我尝试什么,我都无法让 CardView 填充屏幕的宽度。 RecyclerView 的宽度与父容器(手机屏幕)匹配,每个 CardView 与其父容器(RecyclerView)的宽度匹配。 Android Studio 中的设计面板显示 CardView 应该拉伸到屏幕边缘,但事实并非如此。
这是 RecyclerView 布局的 XML: `
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.example.weatherapp.home.HomeViewModel"/>
</data>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/locations_list"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:scrollbars="vertical"
app:listData="@{viewModel.locList}"/>
</layout>
`
这是 RecyclerView 中每个项目的布局的 XML: `
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View" />
<variable
name="location"
type="com.example.weatherapp.entity.Entry" />
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/cityName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{location.cityName}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:text="@{location.stateName}"
android:visibility="@{location.stateVisibility}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:text="@{location.countryName}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:text="@{location.fTemp}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:text="@{location.weather}" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</layout>
`
编辑:我为 CardView 和 RecyclerView 着色以显示清晰的边界。 CardView 是紫色的,RecyclerView 是绿松石色。
根据 Google 的 LinearLayout 文档,我玩过每个 TextView 的 android:layout_weight 设置,将它们全部设置为 1,将每个的 android:layout_width 设置为 0dp。这并没有将 CardView 拉伸到屏幕边缘,而只是将每个 TextView 缩小。我的目标是让 CardView 伸展到边缘,让 5 个 TextView 在其中均匀分布。
【问题讨论】:
标签: android kotlin user-interface android-recyclerview android-linearlayout