您的位置:首页 > 编程语言

代码改变EditText的password属性值并可查看密码

2016-03-31 15:40 453 查看
代码改变EditText的password属性值并可查看密码,就是在设置密码的时候有的时候需要显示密码,但是有的时候需要隐藏密码

效果去下:



但是在勾选了显示密码时就会显示密码



不废话,看代码。

先是xml代码部分:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="请输入密码"
android:textSize="20dp" />

<EditText
android:id="@+id/ed_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码" >

<requestFocus />
</EditText>

<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:layout_marginLeft="10dip"
android:layout_marginTop="10dip"
android:text="显示密码" />

</LinearLayout>

下面是java代码部分:
package com.eulav.dialog;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class MainActivity extends Activity implements OnCheckedChangeListener {
EditText ed_password;
CheckBox checkbox;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_password = (EditText) findViewById(R.id.ed_password);
ed_password.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
checkbox = (CheckBox) findViewById(R.id.checkBox);
checkbox.setOnCheckedChangeListener(this);
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 显示为普通文本
ed_password
.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
// 使光标始终在最后位置
Editable etable = ed_password.getText();
Selection.setSelection(etable, etable.length());
} else {
// 显示为密码
ed_password.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
// 使光标始终在最后位置
Editable etable = ed_password.getText();
Selection.setSelection(etable, etable.length());
}
}
}
源码免积分下载:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: