2016-10-24 142 views
-1

我想在Android中處理「關閉軟鍵盤」事件,並且據我所知,唯一的解決方法是按照this answer的小類EditTextAndroid軟鍵盤:「完成」「關閉」

這裏是我的類:

public class EditTextCustom extends EditText { 

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

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

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

    @Override 
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 
     super.onFocusChanged(focused, direction, previouslyFocusedRect); 
     if (listener != null) 
      listener.onStateChanged(this, true); 
    } 

    @Override 
    public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) { 
     if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { 
      Log.d("Info", "Soft keyboard was hidden"); 
      if (listener != null) { 
       listener.onStateChanged(this, false); 
      } 
     } 
     return super.onKeyPreIme(keyCode, event); 
    } 

    KeyboardListener listener; 

    public void setOnKeyboardListener(KeyboardListener listener) { 
     this.listener = listener; 
    } 

    public interface KeyboardListener { 
     void onStateChanged(EditTextCustom keyboardEditText, boolean showing); 
    } 
} 

我需要這個事件(S)(KeyEvent.KEYCODE_BACKKeyEvent.ACTION_UP)作爲EditorInfo.IME_ACTION_DONE,就是當用戶是否已經按下駁回軟鍵盤,它是由Android的解釋應用了"Done"和對EditText的編輯。

實現此目的的最佳實踐?

回答

-1
mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() { 

     @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      if (actionId == EditorInfo.IME_ACTION_DONE) { 
       // do something, e.g. set your TextView here via .setText() 
       InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 
       return true; 
      } 
      return false; 
     } 
    }); 

mEtNumber.setOnEditorActionListener(新TextView.OnEditorActionListener(){

 @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      if (actionId == EditorInfo.IME_ACTION_DONE) { 
       // do something, e.g. set your TextView here via .setText() 
       InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 
       return true; 
      } 
      return false; 
     } 
    }); 

和XML

機器人:imeOptions = 「actionDone」

這可能會幫助你

+0

嘗試過,沒有工作 – TranslucentCloud

+0

據我瞭解,當「D一個「被推。我需要在「解除」被推送時採取行動。 – TranslucentCloud