0

我的操作栏 (ActionbarSherlock) 中有一个折叠的搜索 EditView 菜单。当 setShowAsAction 方法设置为 SHOW_AS_ACTION_NEVER 时,键盘显示并且用户可以按预期开始键入。

但是,当我将值设置为 SHOW_AS_ACTION_ALWAYS 时,用户必须在开始输入之前触摸 EditText,因为它似乎没有焦点!

我的代码是否有问题或解决此问题的方法?

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    final MenuItem search = menu.add(0, MENU_SEARCH, MENU_SEARCH, getString(R.string.search));
    search.setIcon(R.drawable.ic_action_search);
    search.setActionView(R.layout.action_search);
    search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case MENU_SEARCH:
            mSearch = (EditText) item.getActionView();
            mSearch.addTextChangedListener(mFilterTextWatcher);
            mSearch.requestFocus();
            mSearch.postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                }
            }, 200);

            break;
    }
    return true;
}

action_search.xml

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:singleLine="true"
          android:hint="@string/search" />
4

1 回答 1

0

解决方案是将片段嵌套在 Activity 中。

public class ProductListActivity extends SherlockFragmentActivity {
    …
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
            ProductListFragment list = new ProductListFragment();
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
        }
    }

    public static class ProductListFragment extends SherlockListFragment {
        …
    }
} 
于 2012-10-10T00:06:14.390 回答