Search code examples
androidandroid-togglebutton

Change EditText value from text to password and vice versa on ToggleButton checked


I am studying programming in Android and I'm hitting an issue. I have this toggle button and when I input a text and the button is on, the text is starred (passworded, call it whatever you want) and when the button is off, the text is a text. However, I am hitting an issue and I don't see the problem. The block of code looks like:

toggleCommand.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(toggleCommand.isChecked()){
                    input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else{
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                }
            }
        });

I don't see the problem. Can you tell me what did I do wrong and explain? When I turn on the application.. I type something in and it's passworded. I press the button to uncheck it and the passworded text turns into a text. I press the button again and instead of getting passworded again, the text stays normal.


Solution

  • Here is the working code:

    toggleCommand.setOnClickListener(new OnClickListener()
        {
    
            @Override
            public void onClick(View arg0)
            {
                if (toggleCommand.isChecked())
                {
                    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                else
                {
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                }
            }
        });
    

    More info: http://thenewboston.org/watch.php?cat=6&number=27

    Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

    edit: Further explanation on setInputType here: http://developer.android.com/reference/android/text/InputType.html