AndroidContext菜单

context菜单为当长按某一个选项时,弹出的菜单实现步骤分三步
① 将某控件注册context 菜单
② 创建context 菜单
③ 为context菜单添加监听

package com.example.gp11_day12_contextmenu;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;

public class MainActivity extends Activity {

private TextView textView;
private float fontSize = 20f;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);

    //1:给需要上下文菜单的视图注册上下文菜单
    //给TextView注册上下文菜单
    //当在视图上长按时,会出现上下文菜单,因为长按时会去回调创建上下文菜单的方法
    registerForContextMenu(textView);
}

//2:创建上下文菜单的回调方法
//当用户长按时,会执行该方法
//参数menu接收的是上下文菜单对象,由系统创建
//参数v接收的是被长按的视图对象
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    //创建上下文菜单,并向菜单中添加菜单项
    getMenuInflater().inflate(R.menu.main, menu);
    super.onCreateContextMenu(menu, v, menuInfo);
}

//3:点击菜单项的事件监听
@Override
public boolean onContextItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch(id)
    {
    case R.id.action_bigFont:
        fontSize+=5;
        textView.setTextSize(fontSize);
        break;
    case R.id.action_smallFont:
        fontSize-=5;
        textView.setTextSize(fontSize);
        break;
    case R.id.action_bgColor:
        //随机生成颜色值
        int red =(int)(Math.random()*256);
        int green =(int)(Math.random()*256);
        int blue =(int)(Math.random()*256);

        textView.setBackgroundColor(Color.rgb(red, green, blue));
        break;
    }  
    return super.onContextItemSelected(item);
}

}

你可能感兴趣的:(AndroidContext菜单)