Reputation: 2795
I am using this sample for my app. This sample doesn't have an action bar.
This is the layout of activity in which I want to add an action bar with options menu:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_gravity="bottom"
android:background="#000"
tools:context="com.example.android.camera2basic.CameraActivity" />
</LinearLayout>
So, LinearLayout
and a FrameLayout
inside of it as a container for fragment. In Main Activity I have implemented onCreateOptionsMenu
and added setSupportActionBar((Toolbar)findViewById(R.id.my_toolbar));
but actionbar with the menu isn't appearing.
How can I add an ActionBar
with menus to this activity?
Upvotes: 0
Views: 5469
Reputation: 46
Set your Activity Theme to NoActionBar and add this 2 lines of Code in your Activity onCreate method.
Add ToolBar in your Layout.
ToolBar toolbar = findViewById ();
setSupportActionBar(toolbar);
Upvotes: 0
Reputation: 1543
Create a main_menu.xml in your menu folder
<item
android:id="@+id/menu1"
android:title="Option 1" />
<item
android:id="@+id/menu2"
android:title="Optiion 2" />
Add this in your activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, 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);
}
Upvotes: 3