1.进入界面就弹出键盘
需求:当用户到登录界面,或者新建界面时,一般情况都需要输入,这个时候可以给某个edittext(可以是必填项)焦点,并弹出键盘。(就不需要用户点击了)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:orientation="horizontal"
android:paddingLeft="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="帐号:"
android:textSize="18sp" />
<EditText
android:id="@+id/et_accounts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入帐号"
android:textColorHint="#cc9999" />
<requestFocus/>
</LinearLayout>
requestFocus:布局里面获取焦点
private void initView() {
etAccount = (EditText) findViewById(R.id.et_accounts);
//代码里面获取焦点
// etAccount.setFocusable(true);
// etAccount.setFocusableInTouchMode(true);
// etAccount.requestFocus();
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(etAccount, 0);
}
警告:对于刚跳到一个新的界面就要弹出软键盘的情况上述代码可能由于界面没有加载完全而无法弹出软键盘。此时应该适当的延迟弹出软键盘如998毫秒(保证界面的数据加载完成)。实例代码如下:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(etAccount, 0);
}
}, 998);
2.返回,或关闭activity没有关闭键盘
代用这个方法
protected void hideInput(){
if(getCurrentFocus()!=null)
{
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(getCurrentFocus()
.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}