How to create Menus(Option, Context, Popup) without creating menu.xml file?

android_learners_hub
How to create Option menu without creating menu.xml file?

Relative Topics

Question : How to create Menus without creating menu.xml file?

Answer : If someone ask you can we create menus without creating menu.xml file? then, you should say yes we can create menu without creating menu.xml file. It is very easy to create . You just have to use add() function for creating menu items and addSubMenu() function for creating submenus with menu. For example, in case of Option menu, you can add menu and submenu as shown below:

public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(groupId,itemId,order,"title1"); // creating menu title1 
        menu.addSubMenu(groupId,itemId,order,"title2").add("title3"); // creating submenu title2 and adding values title3
        return super.onCreateOptionsMenu(menu);
 }

Lets do it step by step:-

Step 1 Create a new project. Open activity_main.xml and create a Text View.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="horizontal">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:id="@+id/text"
android:textAlignment="center"
android:textSize="40sp"
android:text="menu"
android:textColor="?attr/colorError"
/>

</LinearLayout>
Step 2 Open MainActivity.java .Give Reference and Initialize textview and then, 
(for option menu) Create onCreateOptionsMenu() and onOptionsItemSelected() methods.
Here I will create 3 menu Items  in which 2nd menu item will contain 1 submenu item.
package com.example.menu_without_menufile;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import static java.lang.Boolean.TRUE;

public class MainActivity extends AppCompatActivity {
TextView text ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text =findViewById(R.id.text);//Referencing and Initializing

}

/*-----------For Option Menu : onCreateOptionsMenu(Menu menu)----------------------*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0,"About");
menu.addSubMenu(0,1,0,"Settings").add("Size");
menu.add(0,3,0,"Exit");
return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int i=item.getItemId();
// Like the previous post you can also use switch statement here.
// But i am here using if-else statement.
if(i==3)
    {
// I am here appending the text.
text.setText("");
text.append("Exit is selected.\n See you soon\n :)");
}
else
{
Toast.makeText(this, "You selected "+item.getTitle(), Toast.LENGTH_SHORT).show();
}


return super.onOptionsItemSelected(item);
}

}
 Output: When we run above example using an android virtual device (AVD) we will get a result like as shown below.


Do same for Context menu 

*Recall:First register the textview in context view then, write the same code in onCreateContextMenu() and onContextItemSelected() methods.

 Example:-
package com.example.menu_without_menufile;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import static java.lang.Boolean.TRUE;

public class MainActivity extends AppCompatActivity {
TextView text ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text =findViewById(R.id.text);
registerForContextMenu(text);
}
/*----------- For : Context menu----------*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);

menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "About");
menu.addSubMenu(0, v.getId(), 0, "Settings").addSubMenu("size").add("text");
menu.add(0,v.getId(),0,"Exit");
}

@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
// you can get item Id by using item.getItemId().
// and then use to execute different code on each menu item with the help of Switch and if-else Statement
// that I show you in previous posts.
// Here, I fetch Title by using item.getTitle() method and use to to display toast message on different title names.
Toast.makeText(this, item.getTitle()+" is Selected." , Toast.LENGTH_SHORT).show();
return super.onContextItemSelected(item);
}}
Output:









android_learners_hub


Comments