转自Android中密码输入内容可见性切换 - 水寒 - CSDN博客 http://blog.csdn.net/dawanganban/article/details/23374187#comments
效果如图所示:
1.xml布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#D1D1D1"
android:gravity="center"
tools:context="com.lotus.inputpassworddemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:background="#FFFFFF"
android:orientation="horizontal">
<EditText
android:id="@+id/ed_psw"
android:drawableLeft="@mipmap/ic_launcher_round"
android:drawablePadding="8dp"
android:hint="密码(0-16位)"
android:inputType="textPassword"
android:maxLength="16"
android:singleLine="true"
android:background="#00000000"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="50dp" />
<ImageView
android:id="@+id/img_psw"
android:layout_weight="8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/ic_psw_no"/>
</LinearLayout>
</LinearLayout>
2.activity中:
public class MainActivity extends AppCompatActivity {
private EditText ed_psw;
private ImageView img_psw;
boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_psw = (EditText) this.findViewById(R.id.ed_psw);
img_psw = (ImageView) this.findViewById(R.id.img_psw);
img_psw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!flag) {
ed_psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//密码可见
img_psw.setImageResource(R.mipmap.ic_psw_yes);
} else {
ed_psw.setTransformationMethod(PasswordTransformationMethod.getInstance());//密码不可见
img_psw.setImageResource(R.mipmap.ic_psw_no);
}
flag = !flag;
ed_psw.postInvalidate();
//防止每次切换密码可见与不可见后光标会回到行首的情况
CharSequence text = ed_psw.getText();
if (text instanceof Spannable) {
Spannable spanText = (Spannable)text;
Selection.setSelection(spanText, text.length());
}
}
});
}
}