安卓上下文菜单与选项菜单方法基本相似,因为ContextMenu继承了Menu,因此程序可以用相同的方法为它添加菜单项,开发上下文菜单需要重写
onCreateContextMenu(ContextMenu menu,View source,ContextMenu.ContextMenuInfo menuInfo)方法
调用Activity的registerForContextMenu(View view)方法为view组件注册上下文菜单
重写onContextItemSelected(MenuItem mi)方法,绑定监听器
长按文本,将弹出一个菜单项,选择不同菜单项,文字背景将发生不同变化
xml文件
<LinearLayout 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"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择文本背景色"
android:textSize="33sp"/>
</LinearLayout>
.java文件
package com.example.contextmenutest;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView) super.findViewById(R.id.text);
//为TextView注册上下文菜单
registerForContextMenu(text);
}
//创建上下文菜单,需要重写onCreateContextMenu方法
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0,0x111,0,"红色");
menu.add(0,0x112,0,"绿色");
menu.add(0,0x113,0,"蓝色");
//为三个菜单项设置为单选菜单项
menu.setGroupCheckable(0, true, true);
//设置菜单的,图标,标题
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("选择颜色");
}
//为菜单项添加选择事件
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case 0x111:
text.setBackgroundColor(Color.RED);
break;
case 0x112:
text.setBackgroundColor(Color.GREEN);
break;
case 0x113:
text.setBackgroundColor(Color.BLUE);
break;
}
return true;
}
}