ActionBar Sherlock,Fragment和SearchWidget

时间:2013-03-12 11:20:38

标签: android actionbarsherlock options-menu searchview oncreateoptionsmenu


由于标题说我在某些片段中实现搜索小部件时遇到问题。我的问题是,当我使用inflater在onCreateOptionsMenu中膨胀自定义视图时,之后我发现SearchView它总是为空!
如果有人遇到相同或类似的问题,我将不胜感激! :) 我最近两天对此表示不满......这是布局:

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

    <item android:id="@+id/menu_search"
        android:title="Search"
        android:icon="@drawable/abs__ic_search"
        android:showAsAction="always|collapseActionView"
        android:orderInCategory="0"
        android:actionViewClass="com.actionbarsherlock.widget.SearchView"/>

    <item android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@drawable/jk_uma_button_settings_normal"
        android:showAsAction="always"
        android:orderInCategory="1"
         />
</menu>

代码

Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_explore, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                Log.i(TAG, "======================FOCUS TRUE============");
            }else{
                Log.i(TAG, "======================FOCUS FALSE===========");
            }
        }

    });
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, "onCreate");
    api_key = Configuration.get_prefereence_string(getActivity(), "user_activation_key", null);
    user_id = Configuration.get_prefereence_string(getActivity(), "user_id", null);
    setHasOptionsMenu(true);
}

1 个答案:

答案 0 :(得分:4)

据我所知,在onCreate期间调用onCreateOptionsMenu,但是在方法结束时启用了选项菜单功能。尝试在Fragment的构造函数中设置HasOptionsMenu(true)。

public YourFragment() {
    this.setHasOptionsMenu(true);
}

要从活动

按下硬件搜索按钮
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_SEARCH) {
        this.onSearchClicked();
        return true;
    }
    return false;
}