Android Hardware Menu button code not working properly! need help - java

I love this site all you guys are awesome! but here is another problem I have:
In my app I have a webview that displays a website in the entire screen, I have made a code to show a menu through pushing the phone's menu button from where i want 2 things to happen 1st menu item Go back to main screen of the app, 2nd menu item quit the app or exit the app.
First problem:
after pressing the menu button it shows the menu... if I press it again it shows the two choices twice, if I press it again now both items shows 3 times and so on!
Second Problem:
after choosing any of the two choices nothing happens!
here is my code please tell me what I'm doing wrong!
Thanks
menu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menuToMenu"
android:title="Menu Principal"
/>
<item
android:id="#+id/menuToSalir"
android:title="Salir"
/>
</menu>
Backtomain.java
import android.app.Activity;
import android.os.Bundle;
public class Backtomain extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and where I call the menu:
public boolean onPrepareOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater mostrar = getMenuInflater();
mostrar.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menuToMenu:
startActivity (new Intent("my.app.BACKTOMAIN"));
return true;
case R.id.menuToSalir:
finish();
System.exit(0);
return true;
}
return false;
}

You are calling super.onCreateOptionsMenu() from onPrepareOptionsMenu(). And, you are inflating the same options into the menu in onPrepareOptionsMenu(). Rename onPrepareOptionsMenu() to onCreateOptionsMenu(), and it will probably behave better.
Also:
If you think the my.app.BACKTOMAIN activity is running, you probably want to add FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_CLEAR_TOP to the Intent.
Get rid of the menuToSalir menu choice. No well-written Android application will call System.exit(0). Users leave your application by pressing the HOME button, no different than they might in a Web app.

To fix your first problem try onCreateOptionsMenu(), rather than onPrepareOptionsMenu().
I am not positive how to fix second problem, I usually create my menus all in java instead of using xml like you have.

I found the problem it works! I was missing the "s" at...
public boolean onOptionItemSelected(MenuItem item){
the right way is
public boolean onOptionsItemSelected(MenuItem item){
thanks for your help Tim and CommonsWare

I ran into this problem. In my case I had set the background color of the activity screen to black. When the menu popped up it had a transparent background and black text so I didn't see it working.

Related

Disabled menuItem?

Kind people! Tell me how to make such an elementary thing as a disabled menu item with the appropriate appearance, as in the example from material design? Programmatically. Thank you in advance
EDIT: The following examples will disable click, but do not change the appearance according to the material design:
Code example:
#Override
public void onPrepareOptionsMenu(#NonNull Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItem = menu.findItem(R.id.someItem);
menuItem.setEnable(false);
}
Xml example:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/someItem"
android:enabled="false"
android:title="Some title" />
</menu>
You can do Add, Remove, or Disable menu items and change text color of menu item at Runtime like that::
If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)
On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).
On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the app bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().
You can see the Documentation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/someItem"
android:enabled="false"
android:title="Some title"
app:actionViewClass="android.support.v7.widget.TextView"
// if using androidX
//app:actionViewClass="androidx.appcompat.widget.AppCompatTextView"/>
</menu>
And in java code
//sample code
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
//disable menu item and change text color
MenuItem menu1 = menu.findItem(R.id.yourmenuid);
menu1.setEnabled(false);
TextView textView = (TextView) menu1.getActionView();
textView.setTextColor(Color.BLACK);
return true;
}
you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().
I found a workaround on how to change the text color in the menu item. It is extremely sad that such an elementary thing is not provided out of the box. Perhaps someone has a better solution, I'll be glad to see!
MenuItem menuItem = menu.findItem(R.id.some_item);
menuItem.setEnabled(false);
SpannableString s = new SpannableString(menuItem.getTitle());
s.setSpan(new ForegroundColorSpan(Color.GRAY), 0, s.length(), 0);
menuItem.setTitle(s);
Result:

Return to the main activity

I have the following question: when I return from one activity to another, I need certain element of menu to be opened. For example:
Now, when I click "Up" in my activity the first element of menu is always opened (where the running man is drawed). And I need to make such element opened, which was opened before opening new activity. For example I choose an article in Articles menu element and after clicking Up in new activity I want to be opened Articles element again. I tried to realize it as clicking on Back button:
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
But it didn't help. What's the matter?
I think you have to keep the selected item and after returning manually select it.
See the example here: https://stackoverflow.com/a/43117486/7469860
In your Manifest file, search for your Activity node and add the following line:
android:launchMode="singleTask"
This will define how your activity will be launched.
Here is an official documentation about launchMode property https://developer.android.com/guide/topics/manifest/activity-element#lmode

Can't hide actionbar menu item programatically

I'm trying to hide an Actionbar menu item if a shared preference is false.
I'm getting the shared preference as I want, but the menu item wont hide.
// Inflate a menu to be displayed in the toolbar
toolbar.inflateMenu(R.menu.activity_main_actionbar);
// Enable disable set start page item
if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
}
What am i doing wrong??
The right place for doing this is onPrepareOptionsMenu. From the docs,
Prepare the Screen's standard options menu to be displayed. This is
called right before the menu is shown, every time it is shown. You can
use this method to efficiently enable/disable items or otherwise
dynamically modify the contents.
So, I would recommend you to override onPrepareOptionsMenu and then check for the Shared Prefs inside it and show menu accordingly. Something like,
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Enable disable set start page item
if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
}
return true;
}
try this
mToolbar.getMenu().findItem(id).setEnabled(false);
I hope it will work for you.
try this
invalidateOptionsMenu();
I hope it is helpful for you.
Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly.
Update: A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:
MenuItem item = menu.findItem(R.id.addAction);
Start by saving the menu globally in your activity-
Menu menuu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menuu=menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Have different menu.xml for you . one is having noitem and other is
containing the items you want.
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.afixi.prasenjeetpati.notification_service.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
menu_blank.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.afixi.prasenjeetpati.notification_service.MainActivity">
</menu>
Now to remove the option menu at any time do this-
menuu.clear();
getMenuInflater().inflate(R.menu.menu_blank, menuu);
and to get back the normal menu-
menuu.clear();
getMenuInflater().inflate(R.menu.menu_main, menuu);

Android Action Bar Search

I am a newcomer to android and am using Eclipse to learn to write action bars.
Code for res/menu/main:
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="ifRoom" />
Code for MainActivity.java:
public boolean OnOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
However, there is a bug regarding R.id.action_search. It is said that it cannot be resolved or is not a field. How can I solve it?
One more question, am I going to define openSearch() and openSettings by myself or they are defined?
Thank you very much.
I believe that your project have to be built automatically to have the R.id working properly.
For your second question, if you want to open the system settings you should look here: How to open Settings of Android Phone on a button click in our Android App
For the search, I don't know if you're looking for a search bar or opening Google search, but for a search bar you should look at the section Add an action view on this page: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

How to hide menubar but still access it through menubutton

So this is the deal, I have the following
And I want to remove it but still be able to access the menu item through the menu button, is this possible?
Here is my menu xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/updateShares"
android:orderInCategory="100"
android:showAsAction="never"
android:title="Refresh"/>
</menu>
And here is my code creating the menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_action_bar_main, menu);
return true;
}
EDIT_____________________________________________________________________
I still want the "refresh" menu to appear when you press the menu button on the phone, I just want to remove the menu bar, thats why I can't set any option menu to visible=false because then I can't see them when pressing the menu bar.
I am not sure with the mark166 answer. You can try this link also. And another thing what i have done and you can try is....
Just don't inflate the layout on click of Menu. Even dont create menu.xml file.
You can try with the following code in java file
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
Toast.makeText(getApplicationContext(), "Do what you want to show here", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
It works for me and using same thing in app.
You just comment your code for the menu and try this one.
Hope it will help you.
You can just add in your onCreate following snippet:
this.requestWindowFeature(Window.FEATURE_NO_TITLE); so your title bar will gone.
This may help you with removing menu item https://stackoverflow.com/a/13099201/1045579
as per your second screenshot change the target SDK version to 4.0.3 so the menu ... will not visible.

Categories