I’ve used this code to place a collapsible View (EditText) in ActionBarSherlock:
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
//Used to put dark icons on light action bar
boolean isLight = false;
menu.add("Search")
.setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.ic_search)
.setActionView(R.layout.collapsible_edittext)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
When I try to set setOnEditorActionListener on the view (by its id), the app crashes:
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch(v.getText().toString(), 3);
return true;
}
return false;
}
});
I need to have a SearchField in ActionBar and perform a search when user presses “Search” key on keyboard, but I don’t know how to bind the setOnEditorActionListener to the view.
I assume that
R.id.searchis inside yourR.layout.collapsible_edittextlayout? Where are you callingfindViewById()from? For example, are you calling it inonCreate()oronResume()? Are you sure that the menu has been created at this point?I would suggest including it inside
onCreateOptionsMenu(). Something like this may work:The other option would be to inflate the view and attach the listener before calling
MenuItem.setActionView(actionView).(By the way, it is helpful to include the exception and stack trace, if you would like people to determine the cause of a crash.)