保持TextInputLayout始终聚焦或保持标签始终扩展

And*_*oid 17 android android-textinputlayout

我想知道是否有可能始终保持标签扩展,无论是否有文本EditText.我在源头环顾四周,它是一个使用a ValueAnimator和一个counter内部TextWatcher来动画或不动画更改.也许我可以在里面设置一个自定义TextWatcher的自定义?ValueAnimatorEditTextTextInputLayout

Ves*_*sko 8

当前版本的TextInputLayout存在专门做一件事 - 显示/隐藏帮助器标签取决于是否有一些文本EditText.你想要的是不同的行为,所以你需要一个不同的小部件TextInputLayout.这种情况是编写适合您需求的自定义视图的理想选择.

这就是说,你的自定义设置的想法TextWatcherEditText将无法工作或者是因为TextInputLayout不公开它的内部的任何实际处理动画-既不是updateLabelVisibility(),setEditText(),神奇的Handler,做的工作或其他任何东西.当然我们肯定不想去这样的细节的反射路径,所以......

只需使用MaterialEditText!它具有以下属性,可以完全满足您的需求.

met_floatingLabelAlwaysShown:始终显示浮动标签,而不是动画输入/输出.默认为False.

该库非常稳定(我自己在两个不同的项目中使用它)并且有很多自定义选项.希望能帮助到你!


flx*_*pps 8

尽管是最佳答案,我仍然只是想出了一个 Java 反射解决方案来实现所需的行为(使用com.google.android.material.textfield.TextInputLayoutfrom com.google.android.material:material:1.0.0):

/**
 * Creation Date: 3/20/19
 *
 * @author www.flx-apps.com
 */
public class CollapsedHintTextInputLayout extends TextInputLayout {
    Method collapseHintMethod;

    public CollapsedHintTextInputLayout(Context context) {
        super(context);
        init();
    }

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

    public CollapsedHintTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    void init() {
        setHintAnimationEnabled(false);

        try {
            collapseHintMethod = TextInputLayout.class.getDeclaredMethod("collapseHint", boolean.class);
            collapseHintMethod.setAccessible(true);
        }
        catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    @Override
    public void invalidate() {
        super.invalidate();
        try {
            collapseHintMethod.invoke(this, false);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Java 反射当然从来都不是很漂亮,但在我的情况下,它只是比创建一个外观相似的小部件更方便的解决方案,并且链接库似乎已经过时并被废弃了……:/

如果您使用它,请不要忘记添加相应的 ProGuard 规则:

-keepclassmembers class com.google.android.material.textfield.TextInputLayout {
    private void collapseHint;
}
Run Code Online (Sandbox Code Playgroud)


Kas*_*asi 7

对于支持设计23.3.0的我来说,它可以使用

              <android.support.design.widget.TextInputLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:hint="wow such hint"
              app:hintEnabled="true"
              app:hintAnimationEnabled="false"
              />
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于 v25.0.2;文本为空时,标签不会展开。 (3认同)