TextInputLayout 使用辅助类 - CollapsingTextHelper - 来操作其提示文本。这个帮助器的实例是私有的,与它的布局相关的属性都没有暴露,所以我们需要使用一点反射来访问它。此外,每次布置TextInputLayout 时都会设置和重新计算其属性,因此继承TextInputLayout、覆盖其onLayout() 方法并在那里进行调整是有意义的。
import android.content.Context;
import android.graphics.Rect;
import android.support.design.widget.TextInputLayout;
import android.util.AttributeSet;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CustomTextInputLayout extends TextInputLayout {
private Object collapsingTextHelper;
private Rect bounds;
private Method recalculateMethod;
public CustomTextInputLayout(Context context) {
this(context, null);
}
public CustomTextInputLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
adjustBounds();
}
private void init() {
try {
Field cthField = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
cthField.setAccessible(true);
collapsingTextHelper = cthField.get(this);
Field boundsField = collapsingTextHelper.getClass().getDeclaredField("mCollapsedBounds");
boundsField.setAccessible(true);
bounds = (Rect) boundsField.get(collapsingTextHelper);
recalculateMethod = collapsingTextHelper.getClass().getDeclaredMethod("recalculate");
}
catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) {
collapsingTextHelper = null;
bounds = null;
recalculateMethod = null;
e.printStackTrace();
}
}
private void adjustBounds() {
if (collapsingTextHelper == null) {
return;
}
try {
bounds.left = getEditText().getLeft() + getEditText().getPaddingLeft();
recalculateMethod.invoke(collapsingTextHelper);
}
catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
e.printStackTrace();
}
}
}
这个自定义类是常规TextInputLayout 的直接替代品,您可以以同样的方式使用它。例如:
<com.mycompany.myapp.CustomTextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Model (Example i10, Swift, etc.)"
app:hintTextAppearance="@style/TextLabel">
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/bmw"
android:text="M Series" />
</com.mycompany.myapp.CustomTextInputLayout>
注意事项:
在迁移到 Material Components 库时,帮助类和边界的字段名称已删除 m 前缀符号。如 cmets 中所述,它们现在分别命名为 collapsingTextHelper 和 collapsedBounds。
从 API 级别 28 (Pie) 开始,包括反射在内的某些 Restrictions on non-SDK interfaces 可以访问 SDK 中通常无法访问的成员。但是,各种可用的文档似乎表明不禁止对您自己的包中的组件进行反射。由于支持库不是平台 SDK 的一部分,并且在构建时已合并到您的包中,因此该解决方案应该仍然有效。事实上,最近的测试没有发现任何问题,并且在可用的 Pie 模拟器上仍然可以正常工作。