1. 程式人生 > >EditText 無法失焦與失焦後鍵盤不收縮解決方案

EditText 無法失焦與失焦後鍵盤不收縮解決方案

背景

有一個需求,比方說下圖:

點選了上圖的Image 區域才可以編輯。
那麼我首先想到的就是:

android:focusable="false"

不讓它獲取到焦點不就ok嗎?
事實上這是很好的方式,然後我開始編輯點選圖片後EditText獲取焦點:

editText.setSelection(editText.getText().length());//設定焦點位置移到最後,如果沒有這一句,那麼焦點將會在最前
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();// 請求焦點

ps:

editText.setFocusable(true); //物理按鍵可獲得焦點,一般智慧電視機,我們的遙控操作之類
editText.setFocusableInTouchMode(true); ////觸控可獲得焦點

上述如果有一個不為true,android系統都會認為不能獲取焦點。
出現了一個小小的問題,擁有焦點後,居然沒有彈出軟鍵盤。這時候開發者主動點,把它盤出來。

InputMethodManager  inputManager=(InputMethodManager)getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText,InputMethodManager.SHOW_FORCED);

這樣似乎ok了的。
那麼糟糕的情況來了,當我點選EditText的以外的地方的時候,焦點還在Edit上面,焦點並沒有消失。

解決方案

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            View edittext=findViewById(R.id.edittext);
            //判斷是否被點選
            if (!isTouchPointInView(edittext,(int) ev.getX(),(int) ev.getY()))
            {
               edittext.clearFocus();
            }
            break;
    }
    return super.dispatchTouchEvent(ev);
}

我通過判斷如果不在觸控區域內,就讓它失去焦點。
按照這個想法,我的確成功了,然而凡事哪有一帆風順,我遭遇到了另外一個bug。那就是,焦點失去了,然而軟鍵盤還在。
這時候我想到了焦點變動事件,code 如下:

findViewById(R.id.edittext).setOnFocusChangeListener(new View.OnFocusChangeListener(){
    @Override
    public  void onFocusChange(View v,boolean hasFocus)
    {
        EditText editText=(EditText)v;
        if (!hasFocus)
        {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
    }
});

是的,失去了焦點那麼就讓軟鍵盤消失。

其他需要注意的

其他問題,比如頁面back了,或者退出了app,我們都需要手動去讓軟鍵盤隱藏,事件分別是@Override的:onStop與onBackPressed。