一,指定输入类型
1,可以通过input:type指定键盘类型,比如邮件,数字等
2,可以指定是否自动拼写纠错
3,指定ActionButton的行为
默认为next或Done,可以在EditText中通过imeOptions重定义行为,并可以在Activity或者View的onEditorAction中执行;
比如对于EditText先在xml文件中指定imeOptions
<EditText android:id="@+id/search" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/search_hint" android:inputType="text" android:imeOptions="actionSend" />后在EditText的 setOnEditorActionListener中执行
EditText editText = (EditText) findViewById(R.id.search); editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { sendMessage(); handled = true; } return handled; } });
二,显示或者隐藏键盘
1,在Activity启动时自动显示键盘
Activity启动时,会自动focus到首个输入框,但并不会自动显示键盘;需要通过在Activity的声明中指定
android:windowSoftInputMode="stateVisible"
2,手动设置键盘显示或者隐藏
public void showSoftKeyboard(View view) { if (view.requestFocus()) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } }
3,指定键盘显示后ui响应
<application ... > <activity android:windowSoftInputMode="adjustResize" ... > ... </activity> ... </application>
三,支持硬件键盘
1,指定tab键行为
<RelativeLayout ...> <Button android:id="@+id/button1" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:nextFocusForward="@+id/editText1" ... /> <Button android:id="@+id/button2" android:layout_below="@id/button1" android:nextFocusForward="@+id/button1" ... /> <EditText android:id="@id/editText1" android:layout_alignBottom="@+id/button2" android:layout_toLeftOf="@id/button2" android:nextFocusForward="@+id/button2" ... /> ... </RelativeLayout>
2,指定方向键行为
<Button android:id="@+id/button1" android:nextFocusRight="@+id/button2" android:nextFocusDown="@+id/editText1" ... /> <Button android:id="@id/button2" android:nextFocusLeft="@id/button1" android:nextFocusDown="@id/editText1" ... /> <EditText android:id="@id/editText1" android:nextFocusUp="@id/button1" ... />
四,设定键盘的Action
指定键盘的按键行为,通过覆盖activity或者view的onKeyUp等方法
1,处理单键行为
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_D: moveShip(MOVE_LEFT); return true; case KeyEvent.KEYCODE_F: moveShip(MOVE_RIGHT); return true; case KeyEvent.KEYCODE_J: fireMachineGun(); return true; case KeyEvent.KEYCODE_K: fireMissile(); return true; default: return super.onKeyUp(keyCode, event); } }
2,处理复合键的行为
@Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { ... case KeyEvent.KEYCODE_J: if (event.isShiftPressed()) { fireLaser(); } else { fireMachineGun(); } return true; case KeyEvent.KEYCODE_K: if (event.isShiftPressed()) { fireSeekingMissle(); } else { fireMissile(); } return true; default: return super.onKeyUp(keyCode, event); } }