Android 菜单和上下文演示

在Action添加个TextView控件(上下文演示用);

 

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  TextView tv=(TextView)findViewById(R.id.ok);
  this.registerForContextMenu(tv);
 }


 @Override
 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
  //menu.add(0,menu.FIRST+1,1,"老王");
  SubMenu lw=menu.addSubMenu("laowang");
  lw.add(0,menu.FIRST+4,0,"小王 ");
  lw.add(0,menu.FIRST+5,0,"小王8 ");
  menu.add(0,menu.FIRST+2,2,"老李");
  menu.add(0,menu.FIRST+3,3,"老占美国");
  //super.onCreateContextMenu(menu, v, menuInfo);
 }
 @Override
 public boolean onContextItemSelected(MenuItem item) {

  switch (item.getItemId()){
  case Menu.FIRST+1:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  case Menu.FIRST+2:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  case Menu.FIRST+5:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  }
  return true;
 }


 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  //getMenuInflater().inflate(R.menu.main, menu);
  menu.add(0,menu.FIRST+1,0,"老王") ;
  menu.add(0,menu.FIRST+2,0,"老张") ;
  menu.add(0,menu.FIRST+3,0,"老李") ;
  return true;
 }


 public boolean onOptionsItemSelected(MenuItem item) {
  
  switch (item.getItemId()){
  case Menu.FIRST+1:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  case Menu.FIRST+2:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  case Menu.FIRST+3:Toast.makeText(getApplicationContext(),item.getTitle() ,Toast.LENGTH_LONG).show();break;
  }
  return super.onOptionsItemSelected(item);
 }
}

 

posted @ 2017-03-16 10:26  马丁黄瓜啊  阅读(209)  评论(0编辑  收藏  举报