NullPointerException-:尝试在空对象引用上调用接口方法"android.view.View android.view.MenuItem.getActionView()" [英] NullPointerException-: Attempt to invoke interface method "android.view.View android.view.MenuItem.getActionView()' on a null object reference
本文介绍了NullPointerException-:尝试在空对象引用上调用接口方法"android.view.View android.view.MenuItem.getActionView()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Actionbar上添加搜索栏,并在getActionVeiw()上发现了Nullpointer异常.请帮助我简化这个问题,我已经提供了所需的详细信息.
I am trying to add search bar on Actionbar and found Nullpointer exception on getActionVeiw(). Pleaes help me to short out this problem I have provided the required detail.
我的MainActivity扩展了AppCompatActivity并在此行代码上返回错误
My MainActivity extends AppCompatActivity and return error on this line of code
SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
对于我要导入的以上searchview
for above searchview I am importing
import android.support.v7.widget.SearchView;
菜单main.xml文件
Menu main.xml file
<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'
}
推荐答案
请上传完整的代码.
您必须初始化
getMenuInflater().inflate(R.menu.menu_main, menu);
或者您必须delcare
or you have to delcare
MenuInflater inflater = getMenuInflater();
inflater.inflate()
然后在onCreateOptionsMenu()中使用此代码
then use this code in 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;
}
尝试一下.
这篇关于NullPointerException-:尝试在空对象引用上调用接口方法"android.view.View android.view.MenuItem.getActionView()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文