Pietroos
Pietroos

Reputation: 27

Android, adding a menu to an activity

I want to add a menu to my main activity. When I start my application, all shows up correctly but the menu. What I'm doing wrong?

This is my activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<WebView
    android:id="@+id/activity_main_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>

This is part of the MainActivity.java:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.menu1:
            Toast.makeText(this, "Clicked Menu 1", Toast.LENGTH_SHORT).show();
            break;
        case R.id.menu2:
            Toast.makeText(this, "Clicked Menu 2", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

This is the styles.xml

<resources>

    <style name="AppTheme" parent="android:Theme.DeviceDefault.Light">
        <item name="android:statusBarColor">@android:color/black</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>

And for last, this is the menu_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu1"
        android:title="Option 1" />
    <item
        android:id="@+id/menu2"
        android:title="Optiion 2" />
</menu>

Upvotes: 0

Views: 131

Answers (2)

Moreno
Moreno

Reputation: 180

Is your activity extending from AppCompatActivity? Extending from AppCompatActivity allows you to set the toolbar using the method setSupportActionBar check this first.

If not, the 'easy' way would be to use a theme that by default provides you an AppBar (ending with .DarkActionBar for example)

Upvotes: 1

gallosalocin
gallosalocin

Reputation: 985

You need to create a toolbar in your activity_main.xml and in your MainActivity.java in the onCreate add this: setSupportActionBar(yourToolbarId);

Upvotes: 1

Related Questions