You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中MenuItemCompat.getActionView获取SearchView始终为空求助

Fixing Your Empty SearchView Issue in Android Studio

Hey there! No need to apologize about your English—let's get that SearchView working properly together 😊

Looking at your code, I spotted a couple of small mistakes that are causing the SearchView to be null. Let's go through them one by one:

1. Wrong Class Name in Menu XML

In your Menu.xml, the app:actionViewClass value has a typo. You wrote android:support.v7.widget.SearchView (with a colon after android), but it should be a dot instead. This tells the system which exact SearchView class to use.

Corrected 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/action_search1" 
        android:icon="@android:drawable/ic_menu_search" 
        app:showAsAction="always" 
        app:actionViewClass="android.support.v7.widget.SearchView" 
        android:title="@string/search_hint" />
</menu>

2. Outdated Way to Get the SearchView

You're using MenuItemCompat.getActionView(item) to retrieve the SearchView, but since you're extending AppCompatActivity, you can directly use item.getActionView() instead. Also, adding a null check is a good habit to avoid crashes if something goes wrong.

Another key point: make sure you return true from onCreateOptionsMenu—returning super.onCreateOptionsMenu(menu) might prevent the menu from showing up correctly.

Corrected Activity Code:

@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    final MenuItem item = menu.findItem(R.id.action_search1);
    final SearchView searchView = (SearchView) item.getActionView();
    
    // Add a null check to avoid NullPointerException
    if (searchView != null) {
        searchView.setQueryHint("Search Name");
        searchView.setIconified(false);
        searchView.setOnQueryTextListener(this);
    }
    
    return true; // Return true to display the menu
}

3. Double-Check Your Imports

Make sure you're importing the v7 version of SearchView and its listener in your Activity:

import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;

Avoid importing the native android.widget.SearchView—that won't work with the v7 AppCompat library setup you're using.

After making these changes, your SearchView should no longer be null and should display correctly in your SecondActivity.

内容的提问来源于stack exchange,提问作者giew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:51:54