2015-05-26 78 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

不客氣:) –

相關問題