如何检测SearchView是否已扩展?

时间:2015-07-17 23:32:56

标签: android android-actionbar android-appcompat searchview

我有以下菜单项:

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

@Override
public boolean onCreateOptionsMenu( Menu menu ) {
  getMenuInflater().inflate( R.menu.passenger, menu );
  searchItem = menu.findItem( R.id.action_search );
  searchView = (SearchView)MenuItemCompat.getActionView( searchItem );
  searchView.setSubmitButtonEnabled( false );
  return super.onCreateOptionsMenu( menu );
}

我想检查searchView是否已展开。

我尝试了searchItem.isActionViewExpanded()searchView.isHovered(),但没有一个有效。

我错过了什么?

TIA

3 个答案:

答案 0 :(得分:27)

尝试searchItem.isIconified()

  

返回SearchView的当前图标化状态。

     

返回

     

如果SearchView当前已图标化,则为true;如果搜索字段完全可见,则为false。

http://developer.android.com/reference/android/widget/SearchView.html#isIconified%28%29

答案 1 :(得分:11)

searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do what you want when search view expended
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                //do what you want  searchview is not expanded
                return false;
            }
        });

答案 2 :(得分:7)

试试这个,它会检测用户点击搜索图标的时间:

在Kotlin:

    searchView.setOnQueryTextFocusChangeListener { _ , hasFocus ->
        if (hasFocus) {
            // searchView expanded
        } else {
            // searchView not expanded
        }
    }

在Java中:

searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            // searchView expanded
        } else {
            // searchView not expanded
        }
    }
});