Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Context Menu using XML file?

I am using XML file for creating Context Menu for my ListView. (Please see below). I also want to set a header for this Context Menu. I read (at http://www.mail-archive.com/[email protected]/msg43062.html)that I can use menu.setHeaderTitle(myContextMenuTitle) in onCreateContextMenu Method. But I need to set this in XML file. How can I accomplish this?

Following is code for onCreateContextMenu Method, correct me if I am doing anything wrong.. This is my context_menu.xml file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/open" android:title="Open"/>
</menu>

This is my onCreateContextMenu Method:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.context_menu, menu);
  super.onCreateContextMenu(menu, v, menuInfo);
 }

This is my onCreate Method:

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //  extras = getIntent().getExtras();

  registerForContextMenu(getListView());

  ...
 }
like image 217
Vasu Avatar asked Apr 07 '10 11:04

Vasu


People also ask

How do you create a context menu?

Open the app -> Java -> Package -> Mainactivity.In this step, add the code to show the ContextMenu. Whenever the app will strat make a long click on a text and display the number of options to select of them for specific purposes. Comments are added inside the code to understand the code in more detail.

Which method is used to set context menu?

Android context menu appears when user press long click on the element. It is also known as floating menu. It affects the selected content while doing action on it. It doesn't support item shortcuts and icons.


1 Answers

You can call setHeaderTitle("mytitle") method in ,menu object . In override method you get menu object as paramrter of OnCreateContextMenu method. like this:

 @Override
 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
   super.onCreateContextMenu(menu, v, menuInfo);
   menu.setHeaderIcon(R.drawable.icon);
   menu.setHeaderTitle("Share Menu.");
   MenuInflater inflater = getMenuInflater();

   inflater.inflate(R.menu.contextmenu, menu);
 }     
like image 80
Ashish Saini Avatar answered Oct 25 '22 06:10

Ashish Saini