Android软键盘

《每周一记》之Android软键盘

2016-10-29  本文已影响205人  七戈

为之于未有,治之于未乱。

在以往的项目开发中,关于软键盘的知识点一直比较模糊,只是知道简单的使用,当遇到问题的时候,也只能靠度娘或者蒙,刚好最近一个同事询问相关问题时,才发现自己知识的薄弱,正好以此来激励自己不断学习。这也正是这边文章的诞生的原因,更是让我决定开始记录《每周一记》。

参考:官方文档

一、WindowSoftInputMode属性

活动的主窗口如何与包含屏幕上的软键盘窗口交互,这个属性的设置将会影响两件事情:

How the main window of the activity interacts with the window containing the on-screen soft keyboard. The setting for this attribute affects two things:

1、属性详解

The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

此处设置的值(“stateUnspecified”和“adjustUnspecified”除外)将覆盖主题中设置的值。

Values set here (other than "stateUnspecified" and "adjustUnspecified") override values set in the theme.

用来设置窗口软键盘的交互模式,其属性一共有9个取值,分别是:stateUnspecified,stateUnchanged,stateHidden,stateAlwaysHidden,stateVisible,stateAlwaysVisible,adjustUnspecified,adjustResize,adjustPan。

备注:如果我们不设置"adjust..."的属性,对于没有滚动控件的布局来说,采用的是adjustPan方式,而对于有滚动控件的布局,则是采用的adjustResize方式。

2、使用方式
//在activity中的setContentView之前写上以下代码
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//在 项目的AndroidManifest.xml文件中界面对应的<activity>里加入
android:windowSoftInputMode="adjustPan"

二、手动打开、关闭软键盘

在开发过程中,难免会遇到想手动打开或者关闭软键盘的情况,这时使用以下代码不失为一种好办法。

/**
 * 动态显示隐藏软键盘
 *
 * @param context context
 */
public static void toggleSoftInput(Context context) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}

三、软键盘的Enter键

1、使用方式
inputView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                     //do something;              
                    return true;
                }
                return false;
            }
        });

上一篇 下一篇

猜你喜欢

热点阅读