从 child textInputEditText 获取 parent texInputlayout

Get parent texInputlayout from child textInputEditText

我正在实现一项功能,当提示向上浮动时 textInputlayout 提示文本的大小写更改为大写 ,反之亦然。

为此,我在其 child textInputEditText 上使用 OnFocusChangeListener。为了便于实施,我在 activity 上实施 View.OnFocusChangeListener,例如:

public class LoginActivity extends BaseActivity implements View.OnFocusChangeListener

并覆盖 activity 中的方法,如:

@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(findViewById(v.getId()) instanceof TextInputEditText){
        TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent();
        if(hasFocus){
            textInputLayout.setHint(textInputLayout.getHint().toString().toUpperCase());
        }else{
            textInputLayout.setHint(Utility.modifiedLowerCase(textInputLayout.getHint().toString()));
        }
    }
}

在上述方法中,我试图使用行

获取 parent textInputLayout 的视图
TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent();

上面这行代码抛出一个致命错误

java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.design.widget.TextInputLayout

而且非常明显,因为它 returns Framelayout 不能在 textInputLayout

中使用

如果我使用

TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getRootView();

它再次抛出一个致命错误,因为 getRootView() returns DecorView 无法在 textInputLayout

中转换

我的问题是如何从 child textInputEditText 得到 parent textInputLayout?

请指导。

您可以像这样在 TextInputLayout 中添加 id:

<android.support.design.widget.TextInputLayout
    android:id="@+id/nameLayout"
    style="@style/LightInputLayoutNoBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/create_contact_account_data_name"
    app:hintTextAppearance="@style/TextSmall.Bold">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/name"
        style="@style/LightInputFieldNoBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableEnd="@drawable/ic_book_contacts" />

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

并在 activity

中调用 findViewById 到 TextInputLayout

我用下面的代码行解决了这个问题:

TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent().getParent();

根据需要returnstextInputlayout

而不是使用 TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent();,使用像 TextInputEditText et = (TextInputEditText) v; 这样的视图实例,然后 TextInputLayout lay = (TextInputLayout)et.getParent().getParent();