2013-07-02 25 views
1

我在我的Android應用中使用searchview,並且想添加用戶按下以開始搜索的按鈕。根據我在互聯網上閱讀的內容,我可以使用setSubmitButtonEnabled來調用提交按鈕,而不是在佈局文件中放置按鈕。這裏是我的代碼:爲searchView Android應用添加提交按鈕

public void setSubmitButtonEnabled (boolean enabled) { 

} 

我把我的setSubmitButtonEnabled菜單吹氣如下:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.mylist, menu); 

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 
    searchView.setIconifiedByDefault(false); 

    setSubmitButtonEnabled(true); 

    return true; 
} 

顯然我沒有做是正確的,因爲當我啓動我的應用程序,我沒有看到任何提交按鈕在屏幕上。我的代碼中缺少什麼或有什麼問題?謝謝。

+0

http://developer.android.com/guide/topics /search/index.html –

+0

您是否嘗試在搜索視圖中輸入內容?只有當有一些文本要搜索時纔會顯示該按鈕。 – Y2i

+0

是的,我做了,但仍然沒有任何提交按鈕。或者提交按鈕應該出現在我的鍵盤上? – androidnerd

回答

0

僅當SearchView有焦點時纔會顯示提交按鈕。我的解決方法是使用ActionBarSherlockABS),並編輯源代碼以允許即使在ActionBar沒有焦點時顯示提交按鈕。爲此,請按照下列步驟操作:

1.設置ActionBarSherlock項目

爲此,請按照鏈接下載ABS,然後在Eclipse中(或者您喜歡的IDE),去File - >New - >Project...,然後選擇Android - >Android Project from Existing Code。在以下向導中,導航至actionbarsherlock文件夾的位置,然後單擊確定以創建項目。創建後,您可以將其作爲庫添加到現有項目中,方法是前往ProjectPropertiesAndroid然後在底部部分點擊Add...然後選擇actionbarsherlock。最後,按確定。

2.編輯源

要解決這個問題,你需要編輯文件com.actionbarsherlock.widget.SearchView.java。一旦打開,導航到updateSubmitButton(boolean)方法,並註釋掉的代碼

&& hasFocus() 

您的最終方法是這樣的:

private void updateSubmitButton(boolean hasText) { 
    int visibility = GONE; 
    if (mSubmitButtonEnabled && isSubmitAreaEnabled() //&& hasFocus() 
      && (hasText || !mVoiceButtonEnabled)) { 
     visibility = VISIBLE; 
    } 
    mSubmitButton.setVisibility(visibility); 
} 

現在保存,清理項目,並運行 - 現在你會得到你想要的結果。

3.文檔的更改(可選)

您可以使用Modified註解記錄這種變化,例如:

@Modified(author="Phil Brown", summary="Commented out '&& hasFocus()' in order to allow the submit button to be shown without focus to the view.") 
private void updateSubmitButton(boolean hasText) { 
    ... 
}