zoukankan      html  css  js  c++  java
  • Intercept back button from soft keyboard(从软键盘拦截后退按钮)

    onKeyDown() and onBackPressed() doesn't work for this case. You have to use onKeyPreIme.

    Initially, you have to create custom edit text that extends EditText. And then you have to implement onKeyPreIme method which controls KeyEvent.KEYCODE_BACK. After this, one back press enough for solve your problem. This solution works for me perfectly.

    CustomEditText.java

    public class CustomEditText extends EditText {
    
        Context context;
    
        public CustomEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.context = context;
        }
    
        @Override
        public boolean onKeyPreIme(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // User has pressed Back key. So hide the keyboard
                InputMethodManager mgr = (InputMethodManager)         
                    context.getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(this.getWindowToken(), 0);
                // TODO: Hide your view as you do it in your activity
            }
            return false;
    }

    In your XML

    <com.YOURAPP.CustomEditText
         android:id="@+id/CEditText"
         android:layout_height="wrap_content"
         android:layout_width="match_parent"/>

    In your Activity

    public class MainActivity extends Activity {
       private CustomEditText editText;
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          editText = (CustomEditText) findViewById(R.id.CEditText);
       }
    }

    解决方案出版:
    http://stackoverflow.com/questions/3940127/intercept-back-button-from-soft-keyboard

  • 相关阅读:
    Codeforces 每日一练 1213G+961E+1282B2
    AtCoder Beginner Contest 161题解
    Codeforces每日一练 495B+55C+1280C
    CF1062E 线段树/LCA
    Codeforces Round #697 (Div. 3) 题解
    Codeforces Round #511 (Div. 2) A~D题解
    Atcoder ABC 189 题解
    CF1093G 高维曼哈顿距离/线段树
    CF1117D Magic Gems 矩阵快速幂 DP
    CF1106E Lunar New Year and Red Envelopes DP
  • 原文地址:https://www.cnblogs.com/aland/p/4936914.html
Copyright © 2011-2022 走看看