需求:
输入框一旦有值,即显示删除图标;点击切换明密文按钮,可以切换
布局:
<RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"> <EditText android:id="@+id/login_pwd" android:layout_width="match_parent" android:layout_height="match_parent" android:hint="请输入密码" android:paddingLeft="50dp" android:paddingRight="100dp" android:singleLine="true" android:password="true"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:padding="5dp" android:src="@drawable/iconfont_pwd" /> <ImageView android:id="@+id/login_change" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:background="@drawable/display" /> <ImageView android:id="@+id/login_change2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:background="@drawable/display_text" android:visibility="gone" /> <ImageView android:id="@+id/login_pwd_clean" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_marginRight="70dp" android:src="@drawable/search_clear_normal" android:visibility="invisible" /> </RelativeLayout>
代码
//监听密码是否输入 login_pwd.addTextChangedListener(new TextWatcher() { private CharSequence temp; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { temp = s; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (temp.length() > 0) {//限制长度 login_pwd_clean.setVisibility(View.VISIBLE); } else { login_pwd_clean.setVisibility(View.INVISIBLE); } } });
login_pwd_clean.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login_pwd.setText(""); login_pwd_clean.setVisibility(View.INVISIBLE); } });
//密码显示明文 login_change.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LoginActivity.this.login_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); login_change.setVisibility(View.GONE); login_change2.setVisibility(View.VISIBLE); } }); //密码显示密文 login_change2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LoginActivity.this.login_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); login_change2.setVisibility(View.GONE); login_change.setVisibility(View.VISIBLE); } });