As the title says i have a problem implementing search widget in some Fragment. My problem is that when i use inflater to inflate custom view inside a onCreateOptionsMenu and after that I find SearchView it is always null!
If anyone had same or similar problem I would be grateful for some explanation! :)
I banging my head on this for the last two days... Here is the layout:
<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>
Code
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);
}
As far as I know, onCreateOptionsMenu is called during onCreate, but you enable options menu feature in the end of the method. Try to setHasOptionsMenu(true) in the constructor of the Fragment.
public YourFragment() {
this.setHasOptionsMenu(true);
}
To catch hardware search button press from the Activity
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.onSearchClicked();
return true;
}
return false;
}