Thursday, 4 October 2018

Add app bar / action bar / tool bar and menu in Android Studio.

App bar or action bar or tool bar is a dedicated bat on the top of the every app/activity. It is also called title bar of activity. It may contain toolbox/icon or overflow menu or can be both.


So how can we create this action bar in your project?

1. create menu.xml file in res/menu directory of your project. To create go to -

New ---> Android Resource File

Enter the file name (should start with small letters alphabets) then select resource type as menu then click Ok.


Now create menu by adding items in this menu.xml file.

<item android:title="Item 1"></item>
<item android:title="Item 2"></item>
<item android:title="Item 3"></item>
<item android:title="Item 4"></item>

The complete menu.xml is-

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:title="Item 1"></item>
    <item android:title="Item 2"></item>
    <item android:title="Item 3"></item>
    <item android:title="Item 4"></item>
</menu>


2. After creating menu, you require it to inflate on title bar/action bar. To inflate, write given below code in you activity

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

After running your program you can see the menu in action bar, when you click on three dots on left side of action bar like -


If you want to add icon or tool box on the action bar then in menu.xml file, use icon property of item tag and select any .png image from your res/mipmap directory, like (You can see home icon in screen shot given below)  

<item android:title="home"    android:icon="@mipmap/home"    app:showAsAction="always"></item>




No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...