问题
I am implementing a functionality to change the case of textInputlayout
Hint text to upper case when the hint floats up and vice versa.
For that I am using OnFocusChangeListener
on its child textInputEditText
. To make it easy to implement I am implementing View.OnFocusChangeListener
on my activity like:
public class LoginActivity extends BaseActivity implements View.OnFocusChangeListener
and overriding the method in the activity like:
@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()));
}
}
}
In the above method I am trying to get the view of parent textInputLayout
using the line
TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent();
The above line of code throws a fatal error
java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.design.widget.TextInputLayout
and it is very obvious because it returns Framelayout
which cannot be casted in textInputLayout
And if I use
TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getRootView();
it again throws a fatal error because getRootView()
returns DecorView
which cannot be casted in textInputLayout
My question is how to get parent textInputLayout
from child textInputEditText
?
Please guide.
回答1:
I solved the problem with the below line of code:
TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent().getParent();
It returns textInputlayout
as required.
回答2:
You can add id in TextInputLayout like this:
<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>
And call findViewById to TextInputLayout in activity
来源:https://stackoverflow.com/questions/44883544/get-parent-texinputlayout-from-child-textinputedittext