Android中MenuInflater的使用(布局文件定义Menu菜单)

http://mwga.net.blog.163.com/blog/static/106456728201131851230145/

LayoutInflater用法差不多,其用来生成Menu菜单。

 

1.       定义菜单布局文件:option_menu.xml,代码如下:

xml version="1.0" encoding="utf-8"?>

 <menu

   xmlns:android="http://schemas.android.com/apk/res/android">

     <item android:id="@+id/menu_add"

          android:title="Add"

         android:icon="@android:drawable/ic_menu_add"

           />

     <item android:id="@+id/menu_wallaper"

          android:title="Wallpaper"

           android:icon="@android:drawable/ic_menu_gallery"

           />

   <item android:id="@+id/menu_search"

          android:title="Search"

           android:icon="@android:drawable/ic_search_category_default"

           />

   <item android:id="@+id/menu_setting"

          android:title="Settings"

          android:icon="@android:drawable/ic_menu_preferences"

           />

menu>

2.       Java代码:

/** 创建menu菜单

     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)

     */

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

       //获取当前菜单的对象;

       MenuInflater menuInflater=getMenuInflater();

       //菜单层次从一个指定的xml资源去填充

        menuInflater.inflate(R.layout.menu_option//要加载的布局文件的ID;

               menu);  //要填充的菜单;

       return super.onCreateOptionsMenu(menu);

    }

 

 

    /** 菜单选项点击事件的处理

     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)

     */

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

         switch (item.getItemId()) {

       case R.id.menu_add:break;

       case R.id.menu_search:break;

       case R.id.menu_wallaper:break;

       case R.id.menu_setting:showSettings(); break;

       default:

           break;

       }

       return super.onOptionsItemSelected(item);

    }

   

    /**显示系统的设置选项;

     *

     */

     private void showSettings()

     {

       Intent intent=new Intent(android.provider.Settings.ACTION_SETTINGS);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    startActivity(intent);

 }


你可能感兴趣的:(Android)