简体   繁体   中英

Android Toggle Button not working properly for Password Field

When I Click on the Toggle Button, it changes the Password field to Normal looking Text, But when I click on it Again, It doesnt change the Text field to Password Type back. Why is that so ?

Here is my code,

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);
setContentView(R.layout.text);
chkcmd = (Button) findViewById(R.id.but3);
passtog = (ToggleButton) findViewById(R.id.tb1);
input = (EditText) findViewById(R.id.et1);
display = (TextView) findViewById(R.id.tv2);
passtog.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View V) {
// TODO Auto-generated method stub

if(passtog.isChecked())
{
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}

else if(!passtog.isChecked())
{
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
}
});

Since the Support Library v24.2.0. you can achivie this very easy

What you need to do is just:

  1. Add the design library to your dependecies

     dependencies { compile "com.android.support:design:25.1.0" } 
  2. Use TextInputEditText in conjunction with TextInputLayout

     <android.support.design.widget.TextInputLayout android:id="@+id/etPasswordLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/password_hint" android:inputType="textPassword"/> </android.support.design.widget.TextInputLayout> 

passwordToggleEnabled attribute will make the password toggle appear

  1. In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"

  2. You can customize your password toggle by using:

app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.

More details in TextInputLayout documentation .

在此处输入图片说明

Besides implementing the ClickListener you should use the CheckChangedListener as below:

 passtog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Save the state here if(isChecked) { input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else { input.setInputType(InputType.TYPE_CLASS_TEXT); } } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM