Search code examples
javaandroidandroid-edittexttextwatcher

Show EditText B when EditText A has letters


All- I am trying to hide EditText B,C until EditText A has at least one character in it. I have tried using a textwatcher...

EditText editText = (EditText) findViewById(R.id.p1); //A
    final EditText editText$ = (EditText) findViewById(R.id.p1$); //B
    final TextView $ = (TextView) findViewById(R.id.$); //C

    editText$.setVisibility(View.INVISIBLE);
    $.setVisibility(View.INVISIBLE);


    editText.addTextChangedListener(new TextWatcher(){

        public void afterTextChanged(Editable arg0) {
        }
        public void beforeTextChanged(CharSequence s, int start,
                int count, int after) {
            }
        public void onTextChanged(CharSequence s, int start,
                int before, int count) {

            if (s.toString() != "" ) {                  
                editText$.setVisibility(View.VISIBLE);
                $.setVisibility(View.VISIBLE);
            }
            else {
                editText$.setVisibility(View.INVISIBLE);
                $.setVisibility(View.INVISIBLE);            
            }
        }
    });

but EditText B (and C) are either always visible or never visible depending on weather or not I declare editText$.setVisibility(View.INVISIBLE); $.setVisibility(View.INVISIBLE); before the TextWatcher. Can someone tell me what I am doing wrong? Thank you for your time!


Solution

  • try using the equals method for comparing the string instead of java operator, like this:

    if (s.toString().equals("") == false ) {  
    

    Another option you have is to test for length instead of equality to "".

    if (s.toString().length() > 0) {