I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.requestpayment,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
Intent intent=new Intent(this,Logout.class);
this.startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
please help
in onCreateOptionsMenu method replace
return super.onCreateOptionsMenu(menu);
by
return true;
and replace super.onOptionsItemSelected(item); in onOptionsItemSelected() by return true
You have to return true in onCreateOptionsMenu() and in onOptionsItemSelected() after starting the activity.
The correct way would be like this.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.requestpayment,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
Intent intent=new Intent(this,Logout.class);
this.startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
If you chain a overridden method to its superclass(i.e call super.someMethod()), it means you are requesting the superclass to handle the implementation on its own.
You should return true here to tell that you successfully inflated the menu in this child Activity OR succesfully handled the onClick() event on the option items.
NOTE: Mostly, you need to chain a superclass method call, where superclass is reponsible for doing some critical stuffs. For eg:
public class ChildActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
//request superclass to do its critical stuffs
super.onCreate(savedInstanceState);
//continue with your logics here
}
Restart Android studio. Let me know if that still persists
Related
I currently have an app which has 4 pages, these pages are being added using fragments by a pageViewer, so that I can swipe between them.
What I want, is to be able to access the 'options' menu (the one which has a 'settings' item in it by default) from each page, so that I can perform commands specifically for one page, such as a 'refresh' item, which refreshes the data in the current page.
Could anyone point me in the right direction?
Thanks!
Each Fragment can declare its own menu, which will be automatically merged with the current activity's menu.
class YourPage extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Signal that this fragment has proper actions
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
// The menu will be added to the action bar
inflater.inflate(R.menu.fragment_page_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_refresh:
{
// Handle the action...
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Here's a complete example that I made, and also a relevant tutorial.
I'm trying to use the SearchView Support v4 version with action bar sherlock.
So i have my search button in the action bar -> when i touch it the keyboard show up and the searchBar too.
My problem is that i need to use the listeners onQueryTextSubmit and onQueryTextChange but they are never fired. I need to use the searh query string and do custom stuff with it.
Here is the full activity.java
public class ActivityMain extends SherlockFragmentActivity implements OnQueryTextListener, DialogFragmentListener {
/**
* PRIVATE ATTRIBUTES
*/
private static final String TAG = "ActivityMain";
private ViewPager _viewPager;
private TabsAdapter _tabsAdapter;
private DialogFiltre _dialogFiltre;
private String _searchCurrentQuery;
// data
private boolean _doubleBackToExitPressedOnce = false;
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
switch ((int) _viewPager.getCurrentItem()) {
case 0:
getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
break;
case 1:
getSupportMenuInflater().inflate(R.menu.action_bar_menu, menu);
break;
case 2:
getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
break;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.action_bar_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(queryTextListener);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Log.i(TAG, "onQueryTextSubmit--");
onSearchClicked(query);
// hide keyboard
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.d(TAG, "onQueryTextChange--");
_searchCurrentQuery = newText.toString();
EtablissementApplication._adapter.getFilter().filter(_searchCurrentQuery);
return true;
}
private void onSearchClicked(String query) {
Log.d(TAG, "onSearchClicked--");
_searchCurrentQuery = query.toString();
EtablissementApplication._adapter.getFilter().filter(_searchCurrentQuery);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
break;
case R.id.search:
break;
case R.id.menu_filtre:
_dialogFiltre = DialogFiltre.newInstance(R.string.menu_filtre, this);
_dialogFiltre.setValidDialogListener(this);
_dialogFiltre.show(getSupportFragmentManager(), null);
break;
}
return super.onOptionsItemSelected(item);
}
You are trying to use a new SearchView instead of using the one created by the SupportMenuInflater.
You setting the listener to different SearchView that you see on the screen.
Also, every time onPrepareOptionsMenu is called, new SearchView is created, and thus it has no listeners set.
Try to do onPrepareOptionsMenu like this:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
switch ((int) _viewPager.getCurrentItem()) {
case 0:
getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
break;
case 1:
getSupportMenuInflater().inflate(R.menu.action_bar_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(queryTextListener);
break;
case 2:
getSupportMenuInflater().inflate(R.menu.empty_menu, menu);
break;
}
return super.onPrepareOptionsMenu(menu);
}
And remove the overridden method
#Override
public boolean onCreateOptionsMenu(Menu menu) { }
Top result in Google so adding a new possible cause that just gave me a headache. Be mindful of which SearchView implementation you reference.
This did not work for me (compiles, does not crash, but listener does not work):
<!--actionbar.xml-->
...
<item android:id="#+id/search"
android:title="#string/action_search"
android:icon="#drawable/ic_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.widget.SearchView"/>
...
// Activity#onCreateOptionsMenu(android.view.Menu)
val searchView: SearchView = menu.findItem(R.id.search).actionView as android.widget.SearchView
searchView.setOnQueryTextListener(...)
This does (compiles, does not crash, and listener works):
<!--actionbar.xml-->
...
<item android:id="#+id/search"
android:title="#string/action_search"
android:icon="#drawable/ic_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView"/>
...
// Activity#onCreateOptionsMenu(android.view.Menu)
val searchView: SearchView = menu.findItem(R.id.search).actionView as androidx.appcompat.widget.SearchView
searchView.setOnQueryTextListener(...)
You may have to set searchView.setOnQueryTextListener(this); on your SearchView reference.
I'm trying to send the user to a new activity using a menu button, and back again. To put it into context, I have a basic calculator that runs when the app is opened (works perfect right now), then I want the user to hit the menu button on his/her phone, (two buttons should pop up Home and Tip Calculator) when the user hits tip calculator it should then load the new activity TipCalculator. Then if the menu button is pressed again, the same two options should appear and the Home button should bring them back to the basic calculator.
This is my Code for the Calculator.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_calculator, menu);
menu.add(Menu.NONE,HOME_MENU_ID,Menu.NONE,"Home");
menu.add(Menu.NONE,SECOND_MENU_ID,Menu.NONE,"Tip Calculator");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case HOME_MENU_ID:
Intent main = new Intent(this,Calculator.class);
startActivity(main);
finish();
return true;
case SECOND_MENU_ID:
Intent second = new Intent(this,TipCalculator.class);
startActivity(second);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
This is the code for the TipCalculator.java
public class TipCalculator extends Calculator{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipcalculator);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_tipcalculator, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Intent main = new Intent(this,Calculator.class);
startActivity(main);
finish();
return super.onOptionsItemSelected(item);
}
}
The menu comes up fine, and the home button will refresh the home page, but the tip calculator button gives me a force close error and crashes on me.
I've got 2 activites : the first, HomepageActiviy, have a search widget that search data using another activity, SearchActivity.
What I want to do is when I go back from SearchActiviy to HomepageActivity, the search widget go collapsed and with a empty text.
I've tried to do this following thing :
public class HomepageActivity extends Activity {
#TargetApi(11)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.projectslist, menu);
if(Build.VERSION.SDK_INT >= 11) {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.homepage_search).getActionView();
ComponentName component = new ComponentName(this, SearchActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(component));
searchView.setIconifiedByDefault(true);
searchView.setQuery("", false);
}
return super.onCreateOptionsMenu(menu);
}
[…]
#TargetApi(11)
#Override
protected void onRestart() {
super.onRestart();
if(Build.VERSION.SDK_INT >= 11)
invalidateOptionsMenu();
launchAsynchronousImageDownload();
}
}
If the widget is well displayed as collapsed, the text in the widget still remember searched text (after I re-open the widget).
How can I reset the text of the widget?
Thanks for any help! ;)
You might also try the following:
searchView.setQuery("", false);
searchView.clearFocus();
this is the magic
searchView.setQuery("", false); // clear the text
searchView.setIconified(true); // close the search editor and make search icon again
in the HomepageActivity insert the onSaveInstanceState function after oncreate function
this function will trigger everytime you open a new activity ,
before opening new activity it will reset the value of Search Widget
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
searchView.setQuery("", false);
searchView.setIconified(true);
}
This worked for me:
First, I declared the menu item variable at the top of the activity:
private MenuItem mSearchMenuItem;
I defined the variable in OnCreateOptionsMenu():
mSearchMenuItem = menu.findItem(R.id.action_search);
I declared invalidateOptionsMenu() in onResume():
#Override
protected void onResume() {
invalidateOptionsMenu();
super.onResume();
}
Lastly, I called collapseActionView() on the menu item in onPrepareOptionsMenu().
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchMenuItem.collapseActionView();
return super.onPrepareOptionsMenu(menu);
}
searchView.setQuery("", false);
searchView.setIconified(false);
I had this problem too and it worked if I put it in onPrepareOptionsMenu.
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setQuery("", false);
// rest of code...
}
Kotlin
Here's a cleaner solution, it fixes the following:
Issue of showing filtered list after screen rotation.
Issue of showing filtered list when the user switches to other app and returns back.
Issue of search menu shifting to the left when the user returns back.
No need to iconify if you are invalidating, it's done automatically.
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
searchView.setQuery("", false)
(activity as YourActivity).invalidateOptionsMenu()
}
Make sure to change YourActivity to the Activity name in which you have your Fragment.
Just found an ugly way to make it work (read comments to see differences):
public class HomepageActivity extends Activity {
// Declaring SearchView as an instance object
private SearchView searchView;
#TargetApi(11)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.projectslist, menu);
if(Build.VERSION.SDK_INT >= 11) {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// Using instance var instead of local var
searchView = (SearchView) menu.findItem(R.id.homepage_search).getActionView();
ComponentName component = new ComponentName(this, SearchActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(component));
searchView.setIconifiedByDefault(true);
// Setting query is not anymore required
//searchView.setQuery("", false);
}
return super.onCreateOptionsMenu(menu);
}
[…]
#TargetApi(11)
#Override
protected void onRestart() {
super.onRestart();
// Do not need to recreate menu
/*if(Build.VERSION.SDK_INT >= 11)
invalidateOptionsMenu();*/
if(Build.VERSION.SDK_INT >= 11) {
// Calling twice: first empty text field, second iconify the view
searchView.setIconified(true);
searchView.setIconified(true);
}
launchAsynchronousImageDownload();
}
}
It's pretty ugly, I think, so if anybody as a better idea, just tell me :)
I am trying an option menu in a class that extends ListAcitivity. How do I add an option menu to this activity, so when I click on the option button an options menu appears at the bottom of the screen.
I searched online but most tutorials refer to this function onCreateOptionsMenu() which is part of Activity class and it does not seem to work in the subclass of ListActivity.
It is Java. ListActivity (and anything that extends it) inherits all of the features and functions of Activity.
Therefore, just overriding onCreateOptionsMenu will work the same.
Boilerplate code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_xml_name, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_id:
// action
break;
}
return true;
}
:)