Android中使EditText失去焦點,edittext禁止彈出鍵盤


在我們的應用中,有時候一進入一個頁面, EditText默認就會自動獲取焦點。彈出輸入法框,用戶體驗很不好,

那么如何取消這個默認行為呢?

ps:這篇文字是一年前寫的,現在有網友再問這個問題,我進行重新編輯--2014.05.07,目前有更好的辦法,第一種方法局限性很強,大家可以使用第二種方法

 

第一種方法:.在網上找了好久,有點監聽軟鍵盤事件的方法,有調用 clearFouse()方法,但是測試了都不行!在對應的 xml中也找不到相應的屬性可以關閉這個默認行為。

后來研究了一下,在其父控件下,添加如下的屬性,就可以完美解決:

android:focusable="true"  
android:focusableInTouchMode="true"

舉例如下:

<LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
         android:focusable
="true" android:focusableInTouchMode="true"
        >
        
        <EditText 
            android:id="@+id/et_enter_msg_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />
        
        <Button 
            android:id="@+id/sent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/send"
            />
        
        
    </LinearLayout>


第二種方法:直接關閉輸入法

    private void closeInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//沒有顯示則顯示
            imm.hideSoftInputFromWindow(mobile_topup_num.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

 調用這個方法體就行了,具體if語句里面的幾個參數,我就借用一個網友的日志來寫把(在此感謝)

1、方法一(如果輸入法在窗口上已經顯示,則隱藏,反之則顯示)
 
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
 
2、方法二(view為接受軟鍵盤輸入的視圖,SHOW_FORCED表示強制顯示)
 
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);  
[java] view plaincopy
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //強制隱藏鍵盤  

3、調用隱藏系統默認的輸入法
 
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  (WidgetSearchActivity是當前的Activity)  

4、獲取輸入法打開的狀態
 
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
boolean isOpen=imm.isActive();//isOpen若返回true,則表示輸入法打開  

 好了,祝大家玩的開心

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM