android - 异常的 WRAP_CONTENT 行为

标签 android android-layout android-wrap-content

WRAP_CONTENT 应该这样做:

Special value for the height or width requested by a View. WRAP_CONTENT means that the view wants to be just large enough to fit its own internal content, taking its own padding into account.

但现实是不同的

如果您创建一个非常长的 TextView ,其高度很大,大于屏幕高度,那么应用于该 TextView 高度的 WRAP_CONTENT 会出现错误行为,因为将 TextView 高度限制为屏幕高度。

android:layout_height="wrap_content"

为什么 WRAP_CONTENT 有这种错误行为?

如何设置 View 以使其内容的大小不受屏幕高度的限制?

完整的 XML 文件(这是一个游戏结束标题的屏幕,文本将被动画化,因为它隐藏在屏幕下方):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/creditsTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/credits_big"
        android:textAlignment="center"
        android:textColor="@color/font"
        android:textSize="@dimen/medium_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>

最佳答案

尝试以下操作以获取 TextView 中文本的真实高度并调整 View 大小以匹配。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mainLayout.doOnLayout {
            val tv = findViewById<TextView>(R.id.creditsTextView)
            val layout = tv.layout
            val lp = tv.layoutParams
            lp.height = layout.height
            tv.layoutParams = lp
        }
    }
}

虽然这行得通,但让我感到有些不安。您可能想看看其他方法来完成您的学分滚动。

关于android - 异常的 WRAP_CONTENT 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522272/

相关文章:

android - 阿拉伯语 + 英语文本在 android TextView 中显示为空

android-layout - HTC Evo 3d 使用什么 Android 布局文件?

android:layout_alignParentBottom ="true"改变Dialog Activity的高度从wrap_content到match_parent

android - marginTop 不适用于 ConstraintLayout 和 wrap_content

android - 在 Android 中以安全的方式将数据保存在 SDCard 上

java - 使用 Jackson 对 HashMap<MyObject, List<Integer> 进行序列化和反序列化

android - 在 onCreateView() fragment 中设置动态布局

android - styles.xml 的 AlertDialog 全息强调色

android - SurfaceView 位于 SurfaceView 之上

android - Relativelayout 不包装其内容