首页 > 解决方案 > 如何使编辑文本下的文本视图通过键盘显示向上推

问题描述

我有以下布局

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/DarkGray"
    android:orientation="vertical">


        <EditText
            android:id="@+id/etCaption"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:layout_weight="1"           
            android:gravity="start|top" />

        <TextView
            android:id="@+id/tvCounter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_gravity="right" />


</LinearLayout>

本质上,编辑文本占据了屏幕,底部的文本视图。

当我点击编辑文本时,键盘会出现,它覆盖了底部的文本视图。

如何确保将 textview 向上推,以便用户在输入编辑文本时可以看到它。

我最初将它作为约束布局,然后将其更改为线性布局,但仍然无法正常工作

谢谢

标签: android

解决方案


一个节点layout_height="match_parent"不会被推向任何方向,因为布局没有空间移动;这应该是layout_height="wrap_content"(“显示布局边界”)。当键盘出现和消失时,添加android:windowSoftInputMode="adjustResize""adjustPan|adjustResize"应调整布局大小。activityManifest.xml

Activity 的主窗口总是调整大小,以便为屏幕上的软键盘腾出空间。

并且材料TextInputLayout提供了(或非常相似的)效果:

TextInputLayout 的剖析

api "com.google.android.material:material:1.0.0"

例如(注意app:counterEnabledapp:counterMaxLength属性):

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:hint="@string/hint_caption"
        android:inputType="textNoSuggestions"
        android:text="@={item.caption}"

        app:counterEnabled="true"
        app:counterMaxLength="50"/>

</com.google.android.material.textfield.TextInputLayout>

推荐阅读