您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Android开发中,使用EditText进行文本输入是一种常见的交互方式
android:id="@+id/edit_text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
android:id="@+id/edit_text_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="20" />
editTextUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 检查用户名可用性
checkUsernameAvailability(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
private final Handler handler = new Handler();
private final Runnable textChangedRunnable = new Runnable() {
@Override
public void run() {
// 执行操作,如网络请求
}
};
editTextSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handler.removeCallbacks(textChangedRunnable);
handler.postDelayed(textChangedRunnable, 500); // 500ms延迟
}
@Override
public void afterTextChanged(Editable s) {
}
});
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
editText.setFilters(new InputFilter[]{filter});
setError()
方法显示错误提示。例如:if (password.length() < 6) {
editTextPassword.setError("密码长度至少为6位");
} else {
editTextPassword.setError(null);
}
onSaveInstanceState()
方法中保存状态:@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("edit_text_content", editText.getText().toString());
outState.putInt("edit_text_selection", editText.getSelectionStart());
}
然后在onCreate()
方法中恢复状态:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText = findViewById(R.id.edit_text);
if (savedInstanceState != null) {
editText.setText(savedInstanceState.getString("edit_text_content"));
editText.setSelection(savedInstanceState.getInt("edit_text_selection"));
}
}
通过以上实践,你可以优化EditText在Android中的文本输入体验。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。