将SearchView与工具栏一起使用,如何在活动加载时打开键盘?

时间:2016-03-09 07:01:56

标签: android searchview

我已经尝试了stackoverflow中提供的其他可能的答案,但它们都没有工作,所以我再次在这里发布。 问题是我想在activity打开时自动打开软键盘,但我尝试过的方法都没有。

我设置SearchView的活动代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.search, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) SelectCityActivity.this.getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = null;
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }

    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(SelectCityActivity.this.getComponentName()));
        searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        searchView.setQueryHint(searchHint);
        searchView.setIconifiedByDefault(false);
        final SearchView finalSearchView = searchView;
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    showInputMethod(view);
                    finalSearchView.onActionViewExpanded();
                }
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                valueAdapter.getFilter().filter(Methods.capitalize(s));
                return true;
            }
        });
    }
    return true;
}

菜单xml文件:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/action_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always" />

</menu>

3 个答案:

答案 0 :(得分:1)

只需在代码中调用此行

即可
searchView.requestFocus();

那就是它。

答案 1 :(得分:0)

将以下代码放在Activity的 onCreate 上:

((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

希望这会对你有所帮助。

答案 2 :(得分:0)

尝试此操作强制打开软键盘:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);