10

使用AutoCompleteTextView時,出現下拉建議列表,軟件鍵盤仍然可見。這是有道理的,因爲鍵入後續字符以縮小列表通常效率更高。AutoCompleteTextView:刪除軟鍵盤而不是建議

但是,如果用戶想瀏覽建議列表,則軟件鍵盤仍然處於非常單調的狀態(當設備處於橫向方向時,這甚至更成爲問題)。如果沒有鍵盤佔用屏幕空間,瀏覽列表會更容易。不幸的是,當您按下後退鍵時,默認行爲將首先刪除列表(即使在後退鍵的軟件版本中,它顯示的圖像表示'按下此鍵將隱藏鍵盤')。

這裏有一個準系統的例子,證明了什麼我談論:

public class Main2 extends Activity { 
    private static final String[] items = { 
      "One", 
      "Two", 
      "Three", 
      "Four", 
      "Five" 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     AutoCompleteTextView actv = new AutoCompleteTextView(this); 
     actv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
     actv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items)); 
     actv.setThreshold(1); 

     LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(LinearLayout.VERTICAL); 
     ll.addView(actv); 

     setContentView(ll); 
    } 
} 

除了這個事實,這是不直觀(返回鍵提示的提示後按將被髮送到鍵盤),它使瀏覽AutoCompleteTextView的建議非常煩人。

什麼是至少侵入性的方式(例如,捕捉每一個活動上onBackPressed()背部和路由,因此肯定不理想),使第一背壓隱藏鍵盤,以及第二刪除建議列表?

回答

22

您可以通過在自定義AutoCompleteTextView中覆蓋onKeyPreIme來實現此目的。

public class CustomAutoCompleteTextView extends AutoCompleteTextView { 

     public CustomAutoCompleteTextView(Context context) { 
      super(context); 
     } 

     public CustomAutoCompleteTextView(Context context, AttributeSet attrs) { 
      super(context, attrs); 
     } 

     public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { 
      super(context, attrs, defStyleAttr); 
     } 

     @Override 
     public boolean onKeyPreIme(int keyCode, KeyEvent event) { 
      if (keyCode == KeyEvent.KEYCODE_BACK && isPopupShowing()) { 
       InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 

       if(inputManager.hideSoftInputFromWindow(findFocus().getWindowToken(), 
        InputMethodManager.HIDE_NOT_ALWAYS)){  
        return true; 
       } 
      } 

      return super.onKeyPreIme(keyCode, event); 
     } 

    } 
+0

良好的解決方案,但它似乎並沒有工作。該鍵被正確抓取並識別(即,hideSoftInputFromWindow被觸發),但鍵盤實際上並未消失。它可能與'EditText'中的某些東西發生衝突,在視圖具有焦點時保持軟鍵盤向上? – 2014-11-23 12:08:18

+0

你可以嘗試getApplicationWindowToken()而不是 – 2014-11-23 12:21:42

+0

同樣的結果仍然不幸 – 2014-11-23 14:39:32

2

設置DismissClickListener這樣

autoCompleteTextView.setOnDismissListener(new AutoCompleteTextView.OnDismissListener() { 
      @Override 
      public void onDismiss() { 
       InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       in.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0); 
      } 
     }); 
+0

這隻在發佈API17後纔有效。 API <17的任何解決方案?謝謝。 – 2016-10-18 06:15:23