Android floating context menu

In this Android, I am going to provide you an example on using a floating context menu in your applications. The floating context menu works in low and high API levels. It is displayed when the user performs a long-click on a view. For example, you can display the floating context menu that has Copy and Paste items when the user performs the long-click on the EditText. For another example, you display the floating context menu that contains Delete or Edit items when the user performs the long-click on a ListView or GridView. In this post, I will implement the first example.

To provide the floating context menu to the user, first you have to register the context menu to the EditText view using the registerForContextMenu() method of your current activity with the view as its parameter. Then you implement the onCreateContextMenu() of your activity to inflate the context menu layout file. After that, you can implement the onContextItemSelected() Method to do any action when an item of the floating context menu is selected.


Now to have a workable example application on providing the floating context menu, create a new Android project. Then in the activity_main.xml file you need an EditText widget.

<RelativeLayout 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"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="com.example.androidexample.MainActivity" >

   <EditText
     android:id="@+id/txtedit"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:gravity="top"
     android:scrollbars="vertical"    
     android:inputType="textMultiLine"
    
     />

</RelativeLayout>


You will create a menu xml file for the floating context menu called contextmenu.xml file in the res/menu folder. This file defines two items: Copy and Paste items of the floating context menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

   <item
     android:id="@+id/itemcopy"
     android:orderInCategory="100"
     android:showAsAction="always"
     android:title="Copy"/>
   <item
     android:id="@+id/itempaste"
     android:orderInCategory="100"
     android:showAsAction="always"
     android:title="Paste"/>

</menu>


Then in the MainActivity class, you register the context menu to the EditText, implement the createContextMenu() and onContextItemSelected() methods as shown below.

package com.example.androidexample;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {
EditText editText;
ClipboardManager clipboardManager;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     editText=(EditText)findViewById(R.id.txtedit);
     editText.setText("Perform a long-click here to display the context menu.");
     // Make the EditText scrollable
     editText.setMovementMethod(new ScrollingMovementMethod());
     //get ClipboardManager object
   clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
   // Register the context menu to the the EditText
     registerForContextMenu(editText);
   }


   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
     return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
     // Handle action bar item clicks here. The action bar will
     // automatically handle clicks on the Home/Up button, so long
     // as you specify a parent activity in AndroidManifest.xml.
     int id = item.getItemId();
     if (id == R.id.action_settings) {
        return true;
     }
     return super.onOptionsItemSelected(item);
   }
   @Override
   public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
     super.onCreateContextMenu(menu, v, menuInfo);
     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.contextmenu, menu);
   }
   @Override
   public boolean onContextItemSelected(MenuItem item) {
    
     switch (item.getItemId()) {
        case R.id.itemcopy:
         copyText();
           return true;
        case R.id.itempaste:
         pasteText();
           return true;
        default:
           return super.onContextItemSelected(item);
     }
   }
  
   public void copyText(){
   //save data to clipboard
   ClipData clipData = ClipData.newPlainText(editText.toString(), editText.getText().toString());
   clipboardManager.setPrimaryClip(clipData);
  
   }
  
   public void pasteText(){
   //read data from clipboard and insert it into the EditText at the cursor position
   ClipData clipData=clipboardManager.getPrimaryClip();
   try{
   int curPos=editText.getSelectionStart();
   String textToPaste=clipData.getItemAt(0).getText().toString();  
   String oldText=editText.getText().toString();
   String textBeforeCursor=oldText.substring(0,curPos);
   String textAfterCursor=oldText.substring(curPos);
   String newText=textBeforeCursor+textToPaste+textAfterCursor;
   editText.setText(newText);
   }catch(NullPointerException e){}
     
  
   }
}

Android-floating-context-menu

Posted by: Dara | post date: 09-29-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.