1 package com.example.android_menu;
2
3 import android.app.Activity;
4 import android.graphics.Color;
5 import android.os.Bundle;
6 import android.view.ContextMenu;
7 import android.view.ContextMenu.ContextMenuInfo;
8 import android.view.MenuItem;
9 import android.view.View;
10 import android.widget.TextView;
11 import android.widget.Toast;
12
13 public class ContextMenuActivity extends Activity {
14 TextView textView;
15
16 @Override
17 protected void onCreate(Bundle savedInstanceState) {
18 super.onCreate(savedInstanceState);
19 setContentView(R.layout.contextmenuactivity);
20 textView = (TextView) findViewById(R.id.itemtext);
21 registerForContextMenu(textView);
22
23 }
24
25 @Override
26 public void onCreateContextMenu(ContextMenu menu, View v,
27 ContextMenuInfo menuInfo) {
28 super.onCreateContextMenu(menu, v, menuInfo);
29
30 menu.add(0, 1, 0, "红色");
31 menu.add(0, 2, 0, "紫色");
32 menu.add(0, 3, 0, "蓝色");
33 menu.setGroupCheckable(0, true, false);
34
35 }
36
37 @Override
38 public boolean onContextItemSelected(MenuItem item) {
39 item.setChecked(true);
40 switch (item.getItemId()) {
41 case 1:
42 Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT)
43 .show();
44 textView.setBackgroundColor(Color.RED);
45 break;
46
47 case 2:
48 Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT)
49 .show();
50 textView.setBackgroundColor(Color.YELLOW);
51 break;
52 case 3:
53 Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_SHORT)
54 .show();
55 textView.setBackgroundColor(Color.BLUE);
56 break;
57 }
58 return super.onContextItemSelected(item);
59 }
60 }
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical" >
6
7 <TextView
8 android:id="@+id/itemtext"
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 android:text="0000"
12 android:textColor="#000000" />
13
14 </LinearLayout>