2015-05-26 80 views
1

我想在工具栏中打开android searchview而不点击搜索图标。这里是XML代码如何在不点击的情况下打开android搜索?

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

和MainActivity中的Java代码。

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

    MenuItem menuItem = menu.findItem(R.id.action_search); 
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); 
    searchView.setQueryHint("Type something..."); 
    int searchPlateId = searchView.getContext() 
      .getResources() 
      .getIdentifier("android:id/search_plate", null, null); 
    View searchPlate = searchView.findViewById(searchPlateId); 
    if (searchPlate != null) { 
     searchPlate.setBackgroundColor(Color.DKGRAY); 
     int searchTextId = searchPlate.getContext() 
       .getResources() 
       .getIdentifier("android:id/search_src_text", null, null); 
     TextView searchText = (TextView) searchPlate.findViewById(searchTextId); 
     if (searchText != null) { 
      searchText.setTextColor(Color.WHITE); 
      searchText.setHintTextColor(Color.WHITE); 
     } 
    } 
    return true; 
} 

这工作和下面的输出屏幕...

enter image description here

所以,当我点击搜索图标下面它输出画面......

enter image description here

什么我想要的是直接的第二个屏幕!

+1

'Activity'做'search.performClick();' –

+0

@logic自动调用'onclik'但是..为什么你不直接在工具栏上放一个'Edittext'并且不要搜索图标?你也可以在你的编辑文字上添加一个图标 – Aspicas

+0

@Aspicas EditText需要被设计成看起来像默认的搜索,而不是使用availbale一个更容易和优先 –

回答

6

尝试初始化后,这一行添加到您的代码SearchView

searchView.setFocusable(true); 

更新:

searchView.setIconified(false) worked 
在'第二onCreate`
+1

然后这个'searchView.setIconified(false);'?根据这个SO问题,它应该是你正在寻找http://stackoverflow.com/questions/14235677/how-do-i-open-the-searchview-programmatically –

+0

'searchView.setIconified(false)'工程!谢谢你的帮助。 –

+0

不客气:) –

相关问题