Android上下文菜单

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值