Search code examples
androidandroid-design-libraryandroid-textinputlayoutandroid-textinputedittext

Get parent texInputlayout from child textInputEditText


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.


Solution

  • I solved the problem with the below line of code:

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

    It returns textInputlayout as required.