18

我正在使用TextInputLayout来显示提示,但我无法将其垂直居中。我总是得到这个:

在此处输入图像描述

当EditText / TextInputEditText中没有文本时,我想将提示垂直居中。我已经尝试了基本的想法(重力、layout_gravity 等)。到目前为止,唯一的方法是添加一些“魔法”填充,但我想以一种更清洁的方式来做。我正在考虑测量顶部提示标签的高度,并在不可见时将其添加为底部边距,并在可见时删除相同的边距,但我还不太了解TextInputLayout源代码。有人知道怎么做吗?

编辑:

我尝试了这个建议的答案:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:background="@color/grey_strong">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:background="@color/red_light"
        android:gravity="center_vertical"
        android:hint="Test"/>

</android.support.design.widget.TextInputLayout>

我明白了:

在此处输入图像描述

“大”提示仍未垂直居中。它有点低于中心,因为“小”提示(在灰色背景中,在顶部,仅在字段聚焦时可见)在顶部占用一些空间并推动EditText

4

11 回答 11

11

这在当前的实现中似乎是不可能的TextInputLayout。但是你可以通过使用TextInputEditText.

假设您有这样的 aTextInputLayout和 a TextInputEditText

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FAA"
    android:hint="Text hint">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/text_input_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#AAF" />

</android.support.design.widget.TextInputLayout>

在此处输入图像描述

在此处输入图像描述

正如您所看到的,TextInputLayout它由一个用于保存小版本提示的顶部区域和一个用于保存大版本提示(以及输入内容)的底部区域组成。当视图失去焦点并且编辑文本为空时,提示在蓝色空间内移动。另一方面,当视图获得焦点或编辑文本中有一些文本时,提示正在移动到红色区域。

所以我们要做的是:

  • TextInputEditText当内部没有焦点和文本时,在底部添加一个额外的填充,这个填充等于红色区域的高度;
  • TextInputEditText当内部有焦点或文本时删除此填充。

结果,视图看起来像这样,大提示垂直居中: 在此处输入图像描述

假设您检索视图如下:

private lateinit var textInputLayout: TextInputLayout
private lateinit var textInputEditText: TextInputEditText

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    ...
    textInputLayout = view.findViewById(R.id.text_input_layout)
    textInputEditText = view.findViewById(R.id.text_input_edit_text)
    ...
}

这是一个实现示例,您可以使用它来计算以像素为单位的顶部红色空间。

private fun getTextInputLayoutTopSpace(): Int {
    var currentView: View = textInputEditText
    var space = 0
    do {
        space += currentView.top
        currentView = currentView.parent as View
    } while (currentView.id != textInputLayout.id)
    return space
}

然后你可以像这样更新填充:

private fun updateHintPosition(hasFocus: Boolean, hasText: Boolean) {
    if (hasFocus || hasText) {
        textInputEditText.setPadding(0, 0, 0, 0)
    } else {
        textInputEditText.setPadding(0, 0, 0, getTextInputLayoutTopSpace())
    }
}

现在你必须在两个地方调用这个方法:当视图被创建时(实际上我们需要等待视图被完全测量)和焦点改变时。

textInputLayout.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
    override fun onPreDraw(): Boolean {
        if (textInputLayout.height > 0) {
            textInputLayout.viewTreeObserver.removeOnPreDrawListener(this)
            updateHintPosition(textInputEditText.hasFocus(), !textInputEditText.text.isNullOrEmpty())
            return false
        }
        return true
    }
})

textInputEditText.setOnFocusChangeListener { _, hasFocus ->
    updateHintPosition(hasFocus, !textInputEditText.text.isNullOrEmpty())
}

一个问题是高度在TextInputLayout变化,因此所有视图都在移动,并且看起来并不真正居中。您可以通过将TextInputLayout内部 a放置在FrameLayout固定高度并将其垂直居中来解决此问题。

最后,您可以为所有内容设置动画。更改填充时,您只需要使用TransitionManager支持库的 。

您可以在此链接中看到最终结果https ://streamable.com/la9uk

完整的代码将如下所示:

布局:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"> <-- Adapt the height for your needs -->

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="#FAA"
        android:hint="Text hint">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/text_input_edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#AAF" />

    </android.support.design.widget.TextInputLayout>

</FrameLayout>

编码:

private lateinit var textInputLayout: TextInputLayout
private lateinit var textInputEditText: TextInputEditText

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    super.onCreateView(inflater, container, savedInstanceState)
    val view = inflater.inflate(R.layout.your_layout, container, false)

    textInputLayout = view.findViewById(R.id.text_input_layout)
    textInputEditText = view.findViewById(R.id.text_input_edit_text)

    textInputLayout.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            // Wait for the first draw to be sure the view is completely measured
            if (textInputLayout.height > 0) {
                textInputLayout.viewTreeObserver.removeOnPreDrawListener(this)
                updateHintPosition(textInputEditText.hasFocus(), !textInputEditText.text.isNullOrEmpty(), false)
                return false
            }
            return true
        }
    })

    textInputEditText.setOnFocusChangeListener { _, hasFocus ->
        updateHintPosition(hasFocus, !textInputEditText.text.isNullOrEmpty(), true)
    }

    return view
}

private fun updateHintPosition(hasFocus: Boolean, hasText: Boolean, animate: Boolean) {
    if (animate) {
        TransitionManager.beginDelayedTransition(textInputLayout)
    }
    if (hasFocus || hasText) {
        textInputEditText.setPadding(0, 0, 0, 0)
    } else {
        textInputEditText.setPadding(0, 0, 0, getTextInputLayoutTopSpace())
    }
}

private fun getTextInputLayoutTopSpace(): Int {
    var currentView: View = textInputEditText
    var space = 0
    do {
        space += currentView.top
        currentView = currentView.parent as View
    } while (currentView.id != textInputLayout.id)
    return space
}

我希望这能解决你的问题。

于 2018-06-11T12:49:56.370 回答
7

当我使用主题"Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"和密码可见性切换按钮时,我遇到了这个问题。

所以我最终根据这个问题的答案创建了自定义类。

之前: 前 之后: 后

自定义类:

package com.mycompany

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewTreeObserver
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.mycompany.R

class CustomTextInputEditText : TextInputEditText {
    //region Constructors
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    //endregion

    //region LifeCycle
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        textInputEditText.setOnFocusChangeListener { _, hasFocus ->
            updateHintPosition(hasFocus, !textInputEditText.text.isNullOrEmpty())
        }
        textInputEditText.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                if ((textInputLayout?.height ?: 0) > 0) {
                    textInputLayout?.viewTreeObserver?.removeOnPreDrawListener(this)
                    updateHintPosition(textInputEditText.hasFocus(), !textInputEditText.text.isNullOrEmpty())
                    return false
                }
                return true
            }
        })
    }
    //endregion

    //region Center hint
    private var paddingBottomBackup:Int? = null
    private var passwordToggleButtonPaddingBottomBackup:Float? = null
    private val textInputEditText: TextInputEditText
        get() {
            return this
        }
    private val textInputLayout:TextInputLayout?
        get(){
            return if (parent is TextInputLayout) (parent as? TextInputLayout) else (parent?.parent as? TextInputLayout)
        }
    private val passwordToggleButton:View?
        get() {
            return (parent as? View)?.findViewById(R.id.text_input_password_toggle)
        }

    private fun updateHintPosition(hasFocus: Boolean, hasText: Boolean) {
        if (paddingBottomBackup == null)
            paddingBottomBackup = paddingBottom

        if (hasFocus || hasText)
            textInputEditText.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottomBackup!!)
        else
            textInputEditText.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottomBackup!! + getTextInputLayoutTopSpace())

        val button = passwordToggleButton
        if (button != null){
            if (passwordToggleButtonPaddingBottomBackup == null)
                passwordToggleButtonPaddingBottomBackup = button.translationY

            if (hasFocus || hasText)
                button.translationY =  - getTextInputLayoutTopSpace().toFloat() * 0.50f
            else
                button.translationY = passwordToggleButtonPaddingBottomBackup!!
        }
    }

    private fun getTextInputLayoutTopSpace(): Int {
        var currentView: View = textInputEditText
        var space = 0
        do {
            space += currentView.top
            currentView = currentView.parent as View
        } while (currentView !is TextInputLayout)
        return space
    }
    //endregion

    //region Internal classes
    data class Padding(val l: Int, val t: Int, val r: Int, val b: Int)
    //endregion
}

用法:

        <com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:hint="Password"
            app:passwordToggleEnabled="true">

            <com.mycompany.CustomTextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword" />

        </com.google.android.material.textfield.TextInputLayout>
于 2019-04-01T11:50:33.790 回答
4

只需在 editText 或其后代中添加 paddingVertical

于 2021-02-19T15:30:34.570 回答
3

该问题已于 2019 年 4 月 5 日解决。这是提交: https ://github.com/material-components/material-components-android/commit/4476564820ff7a12f94ffa7fc8d9e10221b18eb1

您可以使用已解决该错误的新版本和最新版本(2020 年 7 月 23 日)。看看变更日志(“TextInputLayout”部分): https ://github.com/material-components/material-components-android/releases/tag/1.3.0-alpha02

只需更新您的 gradle 中的库:

implementation 'com.google.android.material:material:1.3.0-alpha02'

它对我有用。

于 2020-08-03T13:11:21.447 回答
1

也许有点晚了,但是...基于@JFrite 回复...您可以创建一个类来改进代码:

class TextInputCenterHelper constructor(val textInputLayout: TextInputLayout, val textInputEditText: TextInputEditText){

init {
    textInputLayout.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            if (textInputLayout.height > 0) {
                textInputLayout.viewTreeObserver.removeOnPreDrawListener(this)
                updateHintPosition(textInputEditText.hasFocus(), !textInputEditText.text.isNullOrEmpty(), false)
                return false
            }
            return true
        }
    })

    textInputEditText.setOnFocusChangeListener { _, hasFocus ->
        updateHintPosition(hasFocus, !textInputEditText.text.isNullOrEmpty(), true)
    }
}

private fun updateHintPosition(hasFocus: Boolean, hasText: Boolean, animate: Boolean) {
    if (animate) {
        TransitionManager.beginDelayedTransition(textInputLayout)
    }
    if (hasFocus || hasText) {
        textInputEditText.setPadding(0, 0, 0, 0)
    } else {
        textInputEditText.setPadding(0, 0, 0, getTextInputLayoutTopSpace())
    }
}

private fun getTextInputLayoutTopSpace(): Int {
    var currentView: View = textInputEditText
    var space = 0
    do {
        space += currentView.top
        currentView = currentView.parent as View
    } while (currentView.id != textInputLayout.id)
    return space
}

并使用它:

 TextInputCenterHelper(your_text_input_layout, your_text_input_edit_text)

我希望这可以帮助某人!

于 2019-07-24T08:40:44.313 回答
1

如果您想在中心显示 EditText 提示,请使用此代码

<android.support.design.widget.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.design.widget.TextInputEditText
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:hint="Test"
    android:gravity="center" />

如果要在垂直居中和左对齐中显示 EditText 提示

<android.support.design.widget.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.design.widget.TextInputEditText
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:hint="Test"
    android:gravity="center_vertical" />

或者

<android.support.design.widget.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.design.widget.TextInputEditText
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:hint="Test"
    android:gravity="center|left" />

于 2018-01-10T06:20:46.977 回答
0

找到了解决方案:

    <android.support.design.widget.TextInputLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:layout_width="200dp"
        android:layout_height="90dp"
        android:hint="Test"
        android:gravity="center_vertical" />

90dp 作为高度只是一个例子。如果您可以提供您的 xml,我可以根据您的情况对其进行调整。您只需要设置android:gravity="center_vertical"并且TextInputLayout应该具有wrap_content高度

希望能帮助到你 :)

于 2018-01-09T21:12:42.793 回答
0

这是我们如何实现的

居中提示使用如果要app:boxBackgroundMode="filled"
删除编辑文本底线使用

            app:boxStrokeWidth="0dp"
            app:boxStrokeWidthFocused="0dp"
            app:boxStrokeColor="@color/white"
            app:boxBackgroundColor="@color/white"

完整代码

           <com.google.android.material.textfield.TextInputLayout
            app:boxBackgroundMode="filled"
            app:boxStrokeWidth="0dp"
            app:boxStrokeWidthFocused="0dp"
            app:boxStrokeColor="@color/white"
            app:boxBackgroundColor="@color/white"
            android:id="@+id/layout_main"
            android:paddingVertical="@dimen/dp_6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/dp_4"
            android:hint="@string/your_hint"
            android:paddingHorizontal="@dimen/dp_16"
            app:layout_constraintTop_toTopOf="parent">

               <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/ed_txt"
                android:inputType="textNoSuggestions"
                android:layout_width="match_parent"
                android:layout_height="?listPreferredItemHeightSmall"
                android:gravity="bottom"
                android:paddingVertical="@dimen/dp_8" />

           </com.google.android.material.textfield.TextInputLayout>
于 2021-08-04T13:45:33.670 回答
0

我发现这里发布的解决方案存在一些问题,因此再添加一个更好地涵盖基础的解决方案:

public class CenteredTextInputEditText extends TextInputEditText {

  private Integer paddingBottomBackup = null;

  // region Constructors
  public CenteredTextInputEditText(Context context) {
    super(context);
  }

  public CenteredTextInputEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public CenteredTextInputEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }
  // endregion

  // region LifeCycle
  @Override
  protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (getOnFocusChangeListener() == null) {
      setOnFocusChangeListener((v, hasFocus) -> updateHintPosition(hasFocus));
    }

    getViewTreeObserver()
        .addOnPreDrawListener(
            new OnPreDrawListener() {
              @Override
              public boolean onPreDraw() {
                if (getHeight() > 0) {
                  getViewTreeObserver().removeOnPreDrawListener(this);
                  updateHintPosition(hasFocus());
                  return false;
                }
                return true;
              }
            });
  }
  // endregion

  // region Center hint
  private void updateHintPosition(boolean hasFocus) {
    boolean hasText = getText() != null && !Strings.isNullOrEmpty(getText().toString());
    if (paddingBottomBackup == null) {
      paddingBottomBackup = getPaddingBottom();
    }

    int bottomPadding = paddingBottomBackup;
    if (!hasFocus && !hasText) {
      bottomPadding += getTextInputTopSpace();
    }
    setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), bottomPadding);

    if (hasFocus) {
      KeyboardUtils.openKeyboardFrom(this);
    }
  }

  private int getTextInputTopSpace() {
    View currentView = this;
    int space = 0;
    do {
      space += currentView.getTop();
      currentView = (View) currentView.getParent();
    } while (!(currentView instanceof TextInputLayout));

    return space;
  }
  // endregion

  public void addAdditionalFocusListener(Consumer<Boolean> consumer) {
    setOnFocusChangeListener(
        new OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            consumer.accept(hasFocus);
            updateHintPosition(hasFocus);
          }
        });
  }
}
于 2020-09-16T22:53:57.303 回答
0

我发现将 TextInput Layout 居中的最简单方法是在我的 XML 中启用 SetHelperEnabled 或通过在 TextInputLayout 中以编程方式插入这些属性

app:helperTextEnabled="true"
app:helperText=" "

在此处输入图像描述 在此处输入图像描述

您还可以通过添加paddingTop到内部 EditText 来进一步调整额外的填充

 <androidx.cardview.widget.CardView
    android:id="@+id/cardView2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="32dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/textView2"
    app:layout_constraintTop_toBottomOf="@+id/textViewSeekModText">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="409dp"
        android:layout_height="wrap_content"
        android:background="#FDFDFD"
        app:helperText=" "
        app:helperTextEnabled="true">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:hint="hint" />
    </com.google.android.material.textfield.TextInputLayout>
</androidx.cardview.widget.CardView>
于 2020-11-08T16:49:58.777 回答
-1

我知道这不是最好的解决方案,但它确实有效。您只需向“TextInputEditText”添加填充:

android:paddingTop="18dp"
android:paddingBottom="18dp"

完整示例:

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/inputLoginEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        android:layout_marginTop="5dp"
        android:backgroundTint="@color/light_blue_background"
        android:textColor="@color/blue_button"
        app:hintEnabled="false"
        android:layout_gravity="center"
        app:boxStrokeWidth="0dp"
        app:boxStrokeWidthFocused="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textLabelEmail"
        app:passwordToggleEnabled="false">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etLoginEmail"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:backgroundTint="@color/light_blue_background"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:paddingTop="18dp"
            android:paddingBottom="18dp"
            android:maxLines="1"
            android:textColor="@color/blue_button" />
    </com.google.android.material.textfield.TextInputLayout>

它对我来说很完美。

于 2021-06-02T03:12:11.563 回答