Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Rahul Sharma Avatar asked Jul 03 '17 10:07

Rahul Sharma


2 Answers

I solved the problem with the below line of code:

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

It returns textInputlayout as required.

like image 177
Rahul Sharma Avatar answered Oct 01 '22 09:10

Rahul Sharma


Instead of using TextInputLayout textInputLayout = (TextInputLayout) findViewById(v.getId()).getParent(); use the instance of view like TextInputEditText et = (TextInputEditText) v;and then TextInputLayout lay = (TextInputLayout)et.getParent().getParent();

like image 43
John Mwangi Avatar answered Oct 01 '22 09:10

John Mwangi