Android学习笔记ActionView

概念

案例

1、布局文件
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:layout_marginTop="12dp"
        android:src="@drawable/message" />
</LinearLayout>

img_add.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:layout_marginTop="12dp"
        android:src="@drawable/message" />
</LinearLayout>

img_message.xml和img_add.xml一样的布局

2、菜单资源文件
menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/search"
          android:title="搜索"
          app:actionViewClass="android.widget.SearchView"
          app:showAsAction="always"></item>
    <item android:id="@+id/img1"
        android:title="通讯录"
        app:actionLayout="@layout/img_message"
        app:showAsAction="always"/>
    <item android:id="@+id/img2"
        android:title="添加"
        app:actionLayout="@layout/img_add"
        app:showAsAction="always"/>
</menu>

关键app:actionViewClass="android.widget.SearchView"

3、MainActivity.Java中加载菜单资源文件

//解析菜单资源文件
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

效果:

原文地址:https://www.cnblogs.com/lzpq/p/12994871.html