本例子对textview添加了一个上下文菜单,长按textview会显示菜单
public class MainActivity extends Activity {
private TextView edit;
final int MENU1 = 0x111;
final int MENU2 = 0x112;
final int MENU3 = 0x113;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (TextView) findViewById(R.id.textView1);
registerForContextMenu(edit);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU1:
item.setCheckable(true);
edit.setBackgroundColor(Color.RED);
break;
case MENU2:
item.setCheckable(true);
edit.setBackgroundColor(Color.GREEN);
break;
case MENU3:
item.setCheckable(true);
edit.setBackgroundColor(Color.BLUE);
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0, MENU1, 0, "红色");
menu.add(0, MENU2, 0, "绿色");
menu.add(0, MENU3, 0, "蓝色");
menu.setGroupCheckable(0, true, true);
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("选择背景颜色");
}
}