Search Tutorials

Loading...

Monday, 7 October 2013

Android Context Menu Example

Context Menu will open when we long press on any widget. Here, i will register to Linear Layout with context menu and when we long press on layout than context menu will pop-up.
Just open your main XML file and paste below code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</LinearLayout>


Now open your Java file and paste below code:


package sel.listG; //package name

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.app.Activity;
import android.graphics.Color;


public class MainActivity extends Activity  {
      LinearLayout ll;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ll=(LinearLayout)findViewById(R.id.ll);
            registerForContextMenu(ll);
                 
           
      }
//create context menu
      public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info)
      {
            super.onCreateContextMenu(menu, v, info);
            menu.setHeaderTitle("Change Color");
            menu.setHeaderIcon(R.drawable.icon);
            menu.add(0, v.getId(),0, "RED");
            menu.add(0, v.getId(),1, "GREEN");
         
      }
      
//perform action on selected item
      public boolean onContextItemSelected(MenuItem item)
      {
            if(item.getTitle()=="RED")
            {
                  ll.setBackgroundColor(Color.RED);
            }
            else if(item.getTitle()=="GREEN")
            {
                  ll.setBackgroundColor(Color.GREEN);
            }
            else
            {
                  return false;
            }
            return true;
      }
  }


Now run your code...

1 comment:

  1. not showing any result ,just a white screen

    ReplyDelete

Back to Top