当进入有EditText的页面中,默认EditText会获取焦点,此时可能就会有需求提出,请在进入页面时,弹出软键盘。关于这个问题,实现方法有很多,简直就是条条大路通罗马。借本文梳理下EditText和软件盘的设置的知识点。
1、对于上述的需求曲线解决办法(糊弄测试人员)。在进入页面中不让EditText获取到焦点,只有在触摸输入框时获取到焦点后,才弹出软键盘。实现原理是让EditText的父布局获取到焦点。xml代码如下设置:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<EditText
android:id="@+id/edt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="please input " />
</LinearLayout>
2、实现上述需求的最便捷的两种方法。在清单文件中进行如下设置
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
> </activity>
或者
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustPan|stateAlwaysVisible"
> </activity>
adjustresize 属性设置后软键盘会将整体的布局向上推,不会让其遮挡布局底部的控件,adjustpan属性则不会。
3、在代码中实现上述需求。
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
new Handler(getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(search_name, InputMethodManager.SHOW_FORCED);
}
}, 200);
4、最后献上软键盘的隐藏和显示的两种方法,有助你在代码中灵活的设置来应对各种需求。
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(edt, InputMethodManager.SHOW_FORCED);//edt为EditText控件
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);//edt为EditText控件