Sunday, 14 June 2015

Context menu in android

No comments
Hello friends,today i explorer a Context menu in android. the Context menu is a one types of menu, they can be used for settings like Delete,Search,Copy,Pest,Rename,Move,More etc. Context menu is a one type of Option menu / Menu they display as on Clickable or as on Long clickable.
In this android example we show how to implement Long clickable Context menu in android.

Let's go for coding

CREATE NEW PROJECT

 Step 1: Write code into activity_main.xml

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

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

    </ListView>
    
</LinearLayout>

Step 2: Write code into MainActivity.java

package dev.androidapplink.contextmenuapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView listView1;
// Define contacts
String contacts[] = { "Apple", "Banana", "Cherry", "Mango", "Orange" };

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

listView1 = (ListView) findViewById(R.id.listView1);
// Create ArrayAdapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contacts);
listView1.setAdapter(adapter);

// Register the ListView for Context menu
registerForContextMenu(listView1);
}

// Create long clickable context menus
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("You like fruts?");
// groupId, itemId,  order, title
menu.add(0, v.getId(), 0, "Like");
menu.add(0, v.getId(), 0, "Dont Like");
menu.add(0, v.getId(), 0, "Let Me Show");

}

@Override
// Create toast message if you want
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
Toast.makeText(getApplicationContext(), "I like fruts",
Toast.LENGTH_LONG).show();
} else if (item.getTitle() == "Dont Like") {
Toast.makeText(getApplicationContext(), "I dont like fruts",
Toast.LENGTH_LONG).show();
} else {

return false;
}
return true;

}

}

Step 3: Now Run Your Project:




No comments :

Post a Comment

Follow me Share