jjzjj

android - NullPointerException- : Attempt to invoke interface method "android.view.View android.view.MenuItem.getActionView()' on a null object reference

coder 2023-12-10 原文

我正在尝试在 Actionbar 上添加搜索栏,但在 getActionVeiw() 上发现了 Nullpointer 异常。请帮助我解决这个问题,我已经提供了所需的详细信息。

我的 MainActivity 扩展了 AppCompatActivity 并在这行代码上返回错误

SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();

searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

对于上面的搜索 View ,我正在导入

import android.support.v7.widget.SearchView;

菜单main.xml文件

  <item
        android:id="@+id/action_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView" />

Gradle 文件-

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:support-v4:+'
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}

最佳答案

请上传完整代码。

你必须初始化

getMenuInflater().inflate(R.menu.menu_main, menu); 

或者你必须删除

MenuInflater inflater = getMenuInflater();
inflater.inflate()

然后在 onCreateOptionsMenu() 中使用这段代码

SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

例如-:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        // Associate searchable configuration with the SearchView
        getMenuInflater().inflate(R.menu.menu_main, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

         SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        this.menu = menu;  // this will copy menu values to upper defined menu so that we can change icon later akash

        return true;
    }

试试这个。

关于android - NullPointerException- : Attempt to invoke interface method "android.view.View android.view.MenuItem.getActionView()' on a null object reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34369469/

有关android - NullPointerException- : Attempt to invoke interface method "android.view.View android.view.MenuItem.getActionView()' on a null object reference的更多相关文章

随机推荐