Android EditText用法大全

来源:互联网 发布:淘宝卖鞋子的好店平价 编辑:程序博客网 时间:2024/06/04 17:57
EditText是Android的基本控件之一,使用频率非常之高。
常见使用问题有:
1.如何让EditText不可编辑?
这常见于首页的搜索框。点击搜索框后才真正跳转到搜索页面,而此时的搜索框是不可输入的。
办法:在布局里将其focusAble设置为false。如:
<EditTextandroid: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取得页面焦点,进而在进入1页面时就会自动弹出键盘。
办法:让布局里该EditText失去焦点,常见写法就是把焦点强行指配给其他View,比如它的父节点主动获得焦点。
即在父节点的属性里增加两句话:
android:focusable="true"android:focusableInTouchMode="true"

如下:
<RelativeLayoutandroid: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"><EditTextandroid: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);            }        }    }

0 0
原创粉丝点击