Android 之MenuInflater的使用(布局定义菜单)!

来源:互联网 发布:人资相关书籍知乎 编辑:程序博客网 时间:2024/04/29 23:55
MenuInflater是用来解析定义在menu 目录下的菜单布局文件的,类似于LayoutInflater 是用来解析定义在layout 下的布局文件。传统意义上 的定义菜单感觉比较繁琐,使用MenuInflater 生成菜单会非常清晰简单。以下以Android自带的BluetoothChat示例说明MenuInflater的用法步骤:

1.在menu文件夹下创建菜单布局文件.  示例中为option_menu.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/secure_connect_scan"
          android:icon="@android:drawable/ic_menu_search"
          android:title="@string/secure_connect"
          android:showAsAction="ifRoom|withText" />
    <item android:id="@+id/insecure_connect_scan"
          android:icon="@android:drawable/ic_menu_search"
          android:title="@string/insecure_connect"
          android:showAsAction="ifRoom|withText" />
    <item android:id="@+id/discoverable"
          android:icon="@android:drawable/ic_menu_mylocation"
          android:title="@string/discoverable"
          android:showAsAction="ifRoom|withText" />
</menu>

以上定义了三个菜单项。

2.在Activity中重写onCreateOptionsMenu定义菜单。

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);   //option_menu即为步骤1创建的菜单布局文件
        return true;
    }

3.在Activity中重写菜单选择处理方法onOptionsItemSelected.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
        case R.id.secure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    } 

 
0 0
原创粉丝点击