In this tutorial we will add items in actionbar/toolbar , 3-dot sajian in actionbar/toolbar and handle item clicks. There will be three items in sajian you can add as many as you want. One item will be displayed on action kafe with icon , other two items will be displayed by clicking 3-dot menu...
Step 1: Create a new Project or open new project
Step 2: Create new "Android Resource Directory" by clicking "res>New>Android Resource Directory" , choose sajian from Resource type:
Step 3: Create menu.xml by clicking "menu>New>Menu resource file"
Step 4: Enter an icon in drawable folder by clicking "drawable>New>Image Asset"
Step 5: menu.xml
<?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"><itemandroid:id="@+id/action_one"android:icon="@drawable/ic_action_name"app:showAsAction="always"android:title="Item One"/><itemandroid:id="@+id/action_two"android:title="Item Two"/><itemandroid:id="@+id/action_three"android:title="Item Three"/></menu>
Step 6: activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"tools:context=".MainActivity"><TextViewandroid:text="Hellow World!"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
Step 7: MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action kafe if it is present.getMenuInflater().inflate(R.menu.menu , menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action kafe item clicks here.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id==R.id.action_one){Toast.makeText(this , "Item One Clicked" , Toast.LENGTH_SHORT).show();return true;}else if (id==R.id.action_two){Toast.makeText(this , "Item Two Clicked" , Toast.LENGTH_SHORT).show();return true;}else if (id==R.id.action_three){Toast.makeText(this , "Item Three Clicked" , Toast.LENGTH_SHORT).show();return true;}return super.onOptionsItemSelected(item);}}
0 Response to "Add Items/Menu In Actionbar/Toolbar Android Studio"