2013-02-27 73 views
1

当我单击切换按钮时,它将密码字段更改为正常查看文本,但是当我再次点击它时,它不会将文本字段更改为密码类型。为什么 ?Android切换按钮无法在密码字段中正常工作

这里是我的代码,

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); 
} 
} 
}); 
+0

use Input.TYPE_CLASS_TEXT | Input.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,而不是仅使用Input.TYPE_CLASS_TEXT – Waqas 2013-02-27 10:44:15

回答

0

除开展ClickListener你应该使用CheckChangedListener如下:

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); 
     } 
    } 
    }); 
1

由于支持库v24.2.0。你可以achivie这很容易

您需要做的仅仅是:

  1. 设计库一起添加到您的依赖条件

    dependencies { 
        compile "com.android.support:design:25.1.0" 
    } 
    
  2. 使用TextInputEditTextTextInputLayout

    <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属性将密码切换显示

  • 在你的根布局不要忘记添加xmlns:app="http://schemas.android.com/apk/res-auto"

  • 您可以通过使用自定义密码切换:

  • app:passwordToggleDrawable - 可绘制用作密码输入可见性切换图标。
    app:passwordToggleTint - 用于密码输入可见性切换的图标。
    app:passwordToggleTintMode - 用于应用背景色调的混合模式。

    更多详细信息在TextInputLayout documentation

    enter image description here