Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parametrize options of a menu on Android?

I want to show/hide some options of a menu on an Android application depending of some strings that I will set to true/false on strings.xml file.

As an example, I will have these strings on strings.xml file:

<string name="option1">false</string>
<string name="option2">true</string>
<string name="option3">true</string>

So in this case only option2 and option3 have to be shown.

On the other side, I mean, in code, I tried the following:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    getMenuInflater().inflate(R.menu.main, menu);

    if((getResources().getString(R.string.option1)).equals("false")){
        menu.getItem(R.id.option1).setVisible(false);
    }

    return true;
}

But option1 is still being shown on the menu.

What should I do to parametrize these options? I could just remove these options but I would like that in the future if my clients want these options active again, I could do it easily changing false value to true.

EDIT: Here is my menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/option1"
            android:title="Option 1" />
        <item
            android:id="@+id/option2"
            android:title="Option 2" />
        <item
            android:id="@+id/option3"
            android:title="Option 3" />
        ....
    </group>
</menu>

LAST UPDATE

I have notice that I was getting NullPointerException because the name of the menu was wrong. I have fixed it and now it does not give me any error.

But my problem comes because I have two different layouts that contains two different menus (one in each layout) and I inflate each layout depending of one string that comes on the login.

For example, considering that the string to inflate the first layout is "hello" I display the layouts as follows on onCreate function of my MainActivity:

if("hello".equals(stringForLayout)){
    setContentView(R.layout.activity_main);
}else{
    setContentView(R.layout.activity_main_secondary);
} 

How can I parametrize the options of both menus so if the first one is being shown and I want to hide one option, I would be able to refer to that option of that menu?

Thanks in advance!

like image 696
Francisco Romero Avatar asked May 09 '17 10:05

Francisco Romero


1 Answers

If you use Strings (e.g. s1 & s2), you have to compare them like this:

if(s1.equals(s2)) {...}

Btw.: You can also look at Shared Preferences in the android documentation to get a cleaner solution. There you can define boolean variables for the different menu options.

like image 74
user3728999 Avatar answered Oct 29 '22 18:10

user3728999