2015-12-19 45 views
4

我试图在操作栏上添加搜索栏,并在getActionVeiw()上发现Nullpointer异常。 Pleaes帮我短了这个问题,我已经提供了所需的详细信息。NullPointerException-尝试调用空对象引用的接口方法“android.view.View android.view.MenuItem.getActionView()'

我的MainActivity扩展AppCompatActivity并在此行代码

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

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

上面搜索查看返回错误我进口

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" /> 

摇篮文件 -

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' 
} 
+2

menu.findItem(R.id.action_search)返回null。菜单是否使用正确的xml? – gvmani

回答

6

请上传的完整代码。

你必须初始化

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

,或者你必须delcare

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; 
    } 

试试这个。

相关问题