|
|
Short press the button to run the method onClick(..) in setOnClickListener(..). Long press the button to execute callback code in the onContextItemSelected(..) method. See a toast popup for both and a TextView message from the last action remains. The registerForContextMenu(button1) produces a call to onCreateContextMenu(..) to define the Context Menu.
package com.brainyideas.cmstpu;
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.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ContextMenuApp extends Activity {
public static final int MENU_1 = Menu.FIRST+1;
public static final int MENU_2 = Menu.FIRST+2;
String msg_start = "start";
String msg = "Selected Context Menu is ... ";
TextView textView1;
Button button1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText(msg_start);
button1 = (Button) findViewById(R.id.button1);
button1.setText("long press me (keep finger down)");
button1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
seeToastAndMsg("regular button press");
}
});
registerForContextMenu(button1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("My Context Menu");
menu.add(Menu.NONE, MENU_1, Menu.NONE, "Menu1");
menu.add(Menu.NONE, MENU_2, Menu.NONE, "Menu2");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_1:
seeToastAndMsg(msg + "Menu1");
return(true);
case MENU_2:
seeToastAndMsg(msg + "Menu2");
return(true);
}
return(super.onContextItemSelected(item));
}
void seeToastAndMsg(String toast) {
textView1.setText(toast);
Toast.makeText(
getApplicationContext(),
toast,
Toast.LENGTH_SHORT).show();
}
}<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>