您的位置:首页 > 移动开发 > Android开发

Android EditText用法大全

2016-12-17 18:29 344 查看
EditText是Android的基本控件之一,使用频率非常之高。

常见使用问题有:

1.如何让EditText不可编辑?

这常见于首页的搜索框。点击搜索框后才真正跳转到搜索页面,而此时的搜索框是不可输入的。

办法:在布局里将其focusAble设置为false。如:
<EditText
android:id="@+id/et_mobile"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:focusable="false"
android:inputType="none"
android:singleLine="true"
android:textColor="#000000"
android:textColorHint="#9a9a9a"
android:textSize="@dimen/px28" />


2.如何在进入页面时不自动弹出键盘?

在带EditText的页面布局里,系统会默认让EditText取得页面焦点,进而在进入页面时就会自动弹出键盘。

办法:让布局里该EditText失去焦点,常见写法就是把焦点强行指配给其他View,比如它的父节点主动获得焦点。

即在父节点的属性里增加两句话:
android:focusable="true"
android:focusableInTouchMode="true"


如下:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:focusable="true" android:focusableInTouchMode="true"
android:paddingLeft="10dp"
android:paddingRight="10dp">

<EditText
android:id="@+id/et_comment_rating"
style="@style/CommonEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="left|top"
android:hint="@string/rating_comment"
android:minLines="4"
android:paddingTop="10dp" />
......

</RelativeLayout>


3.如何在进入页面时自动弹出键盘?

正常情况下,如果页面内有EditText,则进入页面时,键盘是会自动弹出的。但是,当它就是异常了,没弹出来怎么办?也有法子。

办法:手动显示和隐藏。

例如:在页面的onCreate方法里通过某个view的post方法延迟调用InputMethodManager的方法,使得页面弹出键盘。
if (ll_content_root.getVisibility() == View.VISIBLE) {
ll_content_root.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 500);
}


这里,主要有如下属性:

3.1. imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 如果键盘在窗口上已经显示,则隐藏,反之则显示。

3.2.强制显示或隐藏:
private void handleKeyboard(boolean isShow) {
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (!isShow) {
if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
if (getCurrentFocus() != null)
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

}
} else {
if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
if (getCurrentFocus() != null)
manager.showSoftInput(et_note, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
4.关于EditText的点击事件。
有时我们会对EditText的点击事件进行埋点统计。对于一个可编辑的EditText来说,首次点击会使EditText获得焦点,获得焦点后后续的点击,才会调用到setOnClickListener的回调。所以这种情况下,建议使用setOnTouchListener来进行统计。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: