Searchview中的Searchview setQuery

时间:2018-04-17 07:59:55

标签: java android android-activity

我有Activity扩展AppCompatActivity。我想在更改屏幕方向后设置searchview查询。我得到了NPE错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setQuery(java.lang.CharSequence, boolean)' on a null object reference

如果我在Fragment中使用setQuery,它可以正常工作。在活动中它不起作用。 如何从活动中更改searchview查询?

MyActivity.java

@Override public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.bankmvp_menu, menu);
    searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    searchManager = (SearchManager) this.getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getComponentName()));
    getObservableSearchViewText();
    return true;
}


@Override public void setQueryToSearch(String querystring) {

        searchView.setQuery(querystring, true); //NPE error

}

bankmvp_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item
    android:id="@+id/action_setmonth"
    android:orderInCategory="100"
    android:title="@string/action_setmonth"
    app:showAsAction="never" />
<item
    android:id="@+id/action_setaccount"
    android:orderInCategory="100"
    android:title="@string/action_setaccount"
    app:showAsAction="never" />
<item
    android:id="@+id/action_nosaveddoc"
    android:orderInCategory="100"
    android:title="@string/action_nosaveddoc"
    app:showAsAction="never" />
<item
    android:id="@+id/action_search"
    android:orderInCategory="100"
    android:title="@string/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always|collapseActionView"
    />
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

1 个答案:

答案 0 :(得分:0)

将查询字符串从Presenter设置为Searchview

  1. 更改menu.xml

    android:id="@+id/action_search"
    android:orderInCategory="100"
    android:title="@string/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:iconifiedByDefault="true" //important
    app:showAsAction="always" //important
    
  2. 更改活动,从Presenter设置仅字符串。

    @Override public void setQueryToSearch(String querystringx) {
    
      if( querystringx.equals("")){
      }else {
        querystring = querystringx;
      }
    
    }
    
  3. 在onResume of activity

    中更改活动setQuery
    if( querystring.equals("")){
    
    }else {
        searchView.setIconified(false);
        searchView.setQuery(querystring, false);
        menuItem.setVisible(true);
    }
    
  4. 更改方向后的屏幕

    enter image description here