首页 > 解决方案 > 在 CardView 中设置 TextView 而不调整视图大小

问题描述

我正在为一个应用程序的设置页面工作,用户需要根据他们的偏好设置文本大小。我正在预览 a 中的一段示例文本,cardView以便他们可以查看并应用他们的更改。我的问题是,随着文本的增加或减少,卡片视图会自行调整。cardView更改文本时如何防止推送其他视图?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="@android:color/white"
    android:layout_height="match_parent"
    <androidx.cardview.widget.CardView
        android:id="@+id/previewView"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        card_view:cardElevation="3dp"
        card_view:cardUseCompatPadding="true"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/previewText"
            android:text="My Text"
            android:fontFamily="@font/muli_bold"
            android:layout_gravity="center"
            android:textSize="29sp"
            android:gravity="center"
            android:textColor="@color/customTextColor"
            android:padding="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </androidx.cardview.widget.CardView>
    <ScrollView
        android:layout_below="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
     //other views here
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

标签: androidtextviewcardview

解决方案


如果我正确理解了这个问题,您只需要为卡片设置一个恒定的高度,如下所示android:layout_height="200dp":所以,不管里面的文字有多大,卡片会保持不变,但文字会被截掉。

这是完整的 CardView 代码:

 <androidx.cardview.widget.CardView
    android:id="@+id/previewView"
    android:layout_margin="10dp"
    android:layout_width="match_parent"
    card_view:cardElevation="3dp"
    card_view:cardUseCompatPadding="true"
    android:layout_height="200dp">
    <TextView
        android:id="@+id/previewText"
        android:text="My Text"
        android:fontFamily="@font/muli_bold"
        android:layout_gravity="center"
        android:textSize="29sp"
        android:gravity="center"
        android:textColor="@color/customTextColor"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</androidx.cardview.widget.CardView>

希望它能解决你的问题。


推荐阅读