1、EditText隐藏输入的密码
利用EditText作为密码输入是现在许多应用程序会用到的方式,下面是两种设置密码隐藏/可见的方式:
在布局文件中设置其password属性:
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"/>
在代码中这样使用:
//设置EditText内容为可见
et01.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//设置EditText内容为不可见
et01.setTransformationMethod(PasswordTransformationMethod.getInstance());
2、监听EditeText用户输入:setOnKeyListener事件
EditText Widget设计的初衷是为了等待User输入而准备的,那么在User输入的同时,就可以使用setOnKeyListener事件对用户在EditText中的按键进行监听并截获,不过这种方式只能监听硬盘事件,无法监听软盘;
还可以使用TextWatcher类,这种方式是可以监听软键盘和硬键盘的,我们只需要实现onTextChanged方法即可,另外TextWatcher还提供了beforeTextChanged和afterTextChanged方法,用于更加详细的输入监听处理。
下面的程序是将截获的内容显示在一个TextView中:
import android.app.Activity;
import android.os.Bundle;
importandroid.text.Editable;
importandroid.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
importandroid.widget.EditText;
importandroid.widget.TextView;
public class MainActivityextends Activity {
TextView textView01;
EditText editText01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView01 = (TextView)findViewById(R.id.textView01);
editText01 = (EditText)findViewById(R.id.editText);
editText01.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, intstart, int before, int count) {
Log.i("输入", s +"/" + start + "/" + before + "/" + count);
textView01.setText(editText01.getText());
}
public void beforeTextChanged(CharSequence s,int start, int count,
int after) {
Log.i("输入", s +"/" + start + "/" + count);
}
public void afterTextChanged(Editable s) {
Log.i("输入", s +"");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action barif it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}