Monday, 12 January 2015

Context menu Example



Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Menus Examaple</string>
    <string name="action_settings">Settings</string>
    <string name="action_share">Share</string>
    <string name="button_context">Show Context</string>

   
</resources>

Main_context.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/item1"
        android:title="@string/action_settings"
        android:icon="@drawable/ic_launcher"></item>
   
    <item android:id="@+id/item2"
        android:title="@string/action_share"
        android:icon="@drawable/ic_launcher"></item>
   
</menu>

Activity_main.xml
<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_context"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/button_context" />

</RelativeLayout>

MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
     }

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

     @Override
     public boolean onContextItemSelected(MenuItem item) {
           if (R.id.item1 == item.getItemId()) {
                Toast.makeText(getApplicationContext(),
                           "You have Clicked on Share Context", Toast.LENGTH_LONG)
                           .show();
           } else if (R.id.item2 == item.getItemId()) {
                Toast.makeText(getApplicationContext(),
                           "You have Clicked on Send Context", Toast.LENGTH_LONG)
                           .show();
           }
           return super.onContextItemSelected(item);
     }   

}

No comments:

Post a Comment