方法二:
使用MenuInflater inflater和xml文件

public void inflate (int menuRes, Menu menu)
Inflate a menu hierarchy from the specified XML resource. Throws InflateException if there is an error.
Parameters:
menuRes  Resource ID for an XML layout resource to load (e.g., R.menu.main_activity)
menu  The Menu to inflate into. The items and submenus will be added to this Menu.

package com.sanjinxiong.XmlMenu;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class XmlMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflater=getMenuInflater();
    	inflater.inflate(R.layout.example, menu);//指定使用的XML
    	return true;
    }
    
    public boolean onPrepareOptionsMenu(Menu menu){
    	
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	switch(item.getItemId()){
    	case R.id.save:
    		Log.v("onOptionsItemSelected","save");
    		break;
    	case R.id.help:
    		Log.v("onOptionsItemSelected","help");
    	case R.id.home:
    		Log.v("onOptionsItemSelected","home");
    	case R.id.exit:
    		Log.v("onOptionsItemSelected","exit");
    	}
    	return true;
    }
       
}

相关文章:

  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2021-11-26
  • 2022-02-22
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-20
  • 2021-07-01
  • 2022-12-23
  • 2021-10-06
相关资源
相似解决方案