---
title: "上下文菜单（Context Menu）（长按TextView弹出）"
author: "AndLi"
date: "2011-10-14T07:50:21Z"
tags: []
categories: ["移动开发"]
slug: "context-menu-textview"
draft: false
lastmod: "2011-10-10T23:43:39Z"
id: 1189154
url: "https://andli.iteye.com/blog/1189154"
---

![](http://dl.iteye.com/upload/attachment/567516/51cbb67f-7a9c-386b-abc8-97f0c18a5355.png)  
 

```
public class MainActivity extends Activity {
	private static final int ITME1 = Menu.FIRST;
	private static final int ITME2 = Menu.FIRST+1;
	private static final int ITME3 = Menu.FIRST+2;
	private TextView myTV;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myTV = (TextView)findViewById(R.id.TextView01);
		registerForContextMenu(myTV);//注册上下文菜单	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, ITME1, 0, "红色背景");
		menu.add(0, ITME2, 0, "绿色背景");
		menu.add(0, ITME3, 0, "白色背景");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ITME1:
			myTV.setBackgroundColor(Color.RED);
			break;
		case ITME2:
			myTV.setBackgroundColor(Color.GREEN);
			break;
		case ITME3:
			myTV.setBackgroundColor(Color.WHITE);
			break;
		}
		return true;
	}
}
```

 

```
<?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/TextView01" android:layout_width="fill_parent"
		android:layout_height="fill_parent" android:text="测试上下文菜单（改变文字背景色）"></TextView>
</LinearLayout>
```