如何创建点击输入时hint移至文本上方的Android EditText?
实现点击输入时Hint上移的Android EditText
方法一:使用Material Design的TextInputLayout 推荐
这是官方提供的最简便方案,自带你要的hint上移动画效果。
- 首先确保项目引入Material库,在app模块的
build.gradle(或build.gradle.kts)中添加依赖:
implementation 'com.google.android.material:material:1.9.0'
(版本可根据项目需求选择最新稳定版)
- 在布局文件中用
TextInputLayout包裹EditText,把hint属性设置在TextInputLayout上:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入内容"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text"/> </com.google.android.material.textfield.TextInputLayout>
默认就会实现:点击EditText获取焦点时,hint平滑上移到输入框上方;失去焦点且输入框为空时,hint回到原位。你还可以通过app:hintTextColor、app:hintTextAppearance等属性自定义hint样式。
方法二:自定义动画实现(不依赖Material库)
如果项目不能用Material库,可通过自定义动画和焦点监听实现:
- 布局文件中定义EditText,预留hint样式调整空间:
<EditText android:id="@+id/customEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入内容" android:textSize="16sp" android:paddingTop="20dp" android:paddingBottom="8dp"/>
- 创建两个动画文件:
res/anim/hint_move_up.xml(上移动画):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="0dp" android:toYDelta="-20dp" android:duration="200"/> <scale android:fromXScale="1.0" android:toXScale="0.8" android:fromYScale="1.0" android:toYScale="0.8" android:pivotX="0dp" android:pivotY="50%" android:duration="200"/> </set>
res/anim/hint_move_down.xml(还原动画):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="-20dp" android:toYDelta="0dp" android:duration="200"/> <scale android:fromXScale="0.8" android:toXScale="1.0" android:fromYScale="0.8" android:toYScale="1.0" android:pivotX="0dp" android:pivotY="50%" android:duration="200"/> </set>
- 在代码中给EditText添加焦点监听,控制动画播放:
val editText = findViewById<EditText>(R.id.customEditText) val hintUpAnim = AnimationUtils.loadAnimation(this, R.anim.hint_move_up) val hintDownAnim = AnimationUtils.loadAnimation(this, R.anim.hint_move_down) // 通过反射获取EditText内部的hint视图 val hintView = editText.javaClass.getDeclaredField("mHintView").apply { isAccessible = true }.get(editText) as TextView editText.setOnFocusChangeListener { v, hasFocus -> val isEmpty = editText.text.toString().isEmpty() if (hasFocus && isEmpty) { hintView.startAnimation(hintUpAnim) hintView.textSize = 12f // 上移后缩小字体 hintView.setTextColor(ContextCompat.getColor(this, R.color.gray)) // 自定义颜色 } else if (!hasFocus && isEmpty) { hintView.startAnimation(hintDownAnim) hintView.textSize = 16f // 还原字体大小 hintView.setTextColor(ContextCompat.getColor(this, R.color.hint_gray)) } }
注意:反射获取mHintView可能因Android版本或EditText实现不同失效,稳定性不如Material库方案。
内容的提问来源于stack exchange,提问作者CookieMonster
相关产品推荐
相关产品推荐

