安卓上下文菜单与选项菜单方法基本相似,因为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;
}
}

更多相关文章

  1. 关于android的反射机制的用法
  2. Android(安卓)Message和obtainMessage的区别
  3. Android(安卓)Kotlin入门-属性和字段
  4. android 通过经纬度获取地址信息
  5. Android开发常用代码
  6. Android监听按键返回键
  7. 安卓中实现两端对齐,中间fill_parent的方法
  8. Android绘制流程窗口启动流程分析(下)
  9. Android设置布局背景为白色的三种方法

随机推荐

  1. Android中如何实现高亮显示即选中状态
  2. Android 3.1 r1 API中文文档(6)――ImageVi
  3. 笔试碎片
  4. Android 开发之日志打印封装log
  5. Android Framework架构浅析之【近期任务
  6. Android UI 介绍1
  7. android device ID获取
  8. 在Android Studio中使用Kotlin。
  9. android 在一个应用中启动另一个应用
  10. Android修改ramdisk.img笔记