1. 程式人生 > >EditText隱藏系統軟鍵盤以及常用屬性

EditText隱藏系統軟鍵盤以及常用屬性

首先我的需求是進入頁面有個EditText,點選要彈出自定義的檢視不能彈出系統的軟鍵盤。於是我想到了搜尋前任造好的輪子原則開始上網搜尋。發現關於EditText隱藏軟鍵盤的方法網上有很多了,但是我試了幾種以後發現沒有任何效果(難道是我開啟的方式不對 )最後還是找到了方法來解決。好了總結一些常用的方法以及最後採用的方法。

第一種方法:在XML檔案下新增: android:focusable=“true” android:focusableInTouchMode=“true” 實驗效果直接無效 第二種方法:直接關閉輸入法 在onCreate中加上: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 第一次進去的時候仍然彈出了系統的軟鍵盤 第三種方法:在Edittext中設定 EditText物件.setInputType(InputType.TYPE_NULL); 軟鍵盤終於不彈出來了,但是游標不見了。。。我去,這是逗我麼。 最後找到的方法

 //隱藏系統自帶的軟鍵盤
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            mPetBirth.setInputType(InputType.TYPE_NULL);
        } else {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(mPetBirth, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

這樣可以隱藏軟鍵盤,游標也存在,但是當你輸入文字之後發現游標一直在第一位。。。這個可以再加一個監聽文字變化的內容監聽器

  // TODO Auto-generated method stub
        mPetBirth.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
    
               mPetBirth.setSelection(mPetBirth.length());
            }
        });

好了,到這一步就完美解決了我的問題了。 接下來總結一些常用的EditText屬性

 <EditText
        android:id="@+id/pet_born"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/px30dp"
        android:background="@null"
        android:hint="  Please enter your pet's birthday"
        android:textColor="@color/color_2e2e2e"
        android:textColorHint="@color/color_9e9e9e"
        android:textCursorDrawable="@drawable/edit_text_cursor"
        android:maxLines="1"
        android:textSize="@dimen/px30sp" />

android:textColorHint="@color/color_9e9e9e"提示文字的顏色 android:textCursorDrawable="@drawable/edit_text_cursor"自定義的游標,你也可以換成你自己想要的圖形 android:background="@null"這一句很重要,這是去掉預設的EditText自帶的下劃線樣式。 好了其餘的屬性也不需要我解釋了。