ContextMenu菜单方法

示例:main.xml



    
    
strings.xml



    OntextMenuExample
    Hello World, MainActivity!
    myButton01
    myButton02
    menuHeader01
    menuHeader02
    Context Menu 01
    Context Menu 02      
main.java

package com.example9.www;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {   
    private TextView button01= null;
    private Button button02= null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button01= (TextView)findViewById(R.id.button01);
        button02= (Button)findViewById(R.id.button02);
        this.registerForContextMenu(button01);
        this.registerForContextMenu(button02);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
        // TODOAuto-generated method stub
    	menu.setHeaderIcon(R.drawable.tp_3);
        if(v == button01){
            menu.setHeaderTitle(R.string.menuHeader01);
            menu.add(20, 20, 20, R.string.conTextMenu01);
            menu.add(20, 21, 21, R.string.conTextMenu02);
        }
        else if(v == button02){
            menu.setHeaderTitle(R.string.menuHeader02);
            menu.add(30, 30, 30, R.string.conTextMenu01);
            menu.add(31, 31, 31, R.string.conTextMenu02);
        }
        super.onCreateContextMenu(menu, v, menuInfo);
    }
    @Override
    public boolean onContextItemSelected(MenuItem item){
    	String str = "";
    	switch(item.getItemId()){
    	case 20:
    		str = "20";
    		break;
    	case 21:
    		str = "21";
    		break;
    	case 30:
    		str = "30";
    		break;
    	case 31:
    		str = "31";
    		break;	
    	}
    	Toast.makeText(getApplicationContext(),str, Toast.LENGTH_LONG).show();
    	return true;
    }
}
知识点:1.registerForContextMenu方法:用于为一个View对象注册上下文菜单,其输入为View对象

2.onCreateContextMenu方法:初始化上下文菜单,在需要相应上下文菜单时调用

3.onContextItemSelected方法:设置上下文中某个菜单被选中时的操作

4.onContextMenuClosed方法:用于设置当前上下文菜单被关闭时的操作,其输入为menu对象



你可能感兴趣的:(The,android,learning,notes)