▲ Android 自定義帶有EditText鍵盤遇到的坑

前言:回了老家瀋陽,進了一家外包公司沒日沒夜的幹活真是心酸。

客戶的需求 需要一個計算器來計算需要的油漆量跟價格,這裏的重頭戲就是輸入重量單價之後計算
這裏寫圖片描述

一開始我個人認爲這沒什麼不就是一個簡單的輸入嘛,然而坑接二連三的出現了

坑一: EditText 會自己調起Android中的軟鍵盤

這裏寫圖片描述

明明自定義了鍵盤,卻偏偏要彈出個軟鍵盤。。。

你肯定會說了,強制關閉軟件盤啊,等什麼啊?

**實驗1 **

 private void hintKb() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

反覆點擊上下兩個EditTextView 依然會彈出軟件盤,所以實驗1作廢

實驗2

EditText et_start_time = (EditText) this.findViewById(R.id.et_start_time);  
              int inType = et_start_time.getInputType();  
              et_start_time.setInputType(InputType.TYPE_NULL);    
              et_start_time.onTouchEvent(event);  
              et_start_time.setInputType(inType);  
              et_start_time.setSelection(et_start_time.getText().length());  

設置之後發現EditText沒有了光標

成功 =使用反射的方式使EditText屏蔽掉了軟鍵盤同時還有光標!==

   public void disableShowSoftInput(EditText tvInputNumber) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            tvInputNumber.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method method;
            try {
                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(tvInputNumber, false);
            } catch (Exception e) {
            }

            try {
                method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(tvInputNumber, false);
            } catch (Exception e) {
            }
        }
    }

坑二: EditText 點擊2次之後才能觸發事件

爲什麼要點擊2次,因爲如當焦點在別的控件上時,只能先點擊獲取焦點,第二次點擊纔會響應,解決辦法改用setOnTouchListener監聽。

  tvInputNumber.setOnTouchListener(new View.OnTouchListener() {
            int touch_flag = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                touch_flag++;
                Log.e("XXX", touch_flag + "");
                if (touch_flag % 2 == 0) {
                //執行自己的方法
                    isDanjia = false;
                    isPut = true;
                }
                return false;
            }
        });

爲什麼%2
我個人的理解手指按下擡起正好是一次觸摸事件,然後就可以可以執行自己的當初設置點擊事件裏面的方法了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章