简单的布局文件
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/name"
android:hint="请输入账号"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<ImageView
android:visibility="gone"
android:clickable="true"
android:id="@+id/del"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/ic_launcher"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et"
android:inputType="numberPassword"
android:hint="请输入密码"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<ImageView
android:clickable="true"
android:id="@+id/im"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#f00"/>
</LinearLayout>
这里的java代码卸载了初始化控件里面
private void initView() {
et = (EditText) findViewById(R.id.et);
im = (ImageView) findViewById(R.id.im);
name = (EditText) findViewById(R.id.name);
del = (ImageView) findViewById(R.id.del);
//给输入账号添加监听事件
name.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
//账号输入不为空的时候就把删除图标显示出来
if (name.getText().length() > 0 && !name.getText().equals("") && name.getText() != null) {
del.setVisibility(View.VISIBLE);
} else {
del.setVisibility(View.GONE);
}
}
});
//给删除图标添加点击事件
del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
name.setText("");
}
});
//密码的显示和隐藏
im.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//默认不显示,点击一次就改变状态,这里只是简单的修改了背景颜色
isSelect = !isSelect;
if (isSelect) {
im.setBackgroundColor(Color.BLACK);
//et.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
im.setBackgroundColor(Color.RED);
//et.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
et.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
//设置光标在最后
et.setSelection(et.getText().length());
}
});
}