2013-04-10 33 views
3

我的屏幕中有一個切換按鈕。如果我點擊這個按鈕,我需要一個鍵盤來顯示在屏幕上。這是我現在所擁有的代碼,但它不顯示爲預期的鍵盤:(以編程方式顯示軟鍵盤 - 不起作用

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     keyboard = (ToggleButton) findViewById(R.id.keyboard); 
     keyboard.setOnClickListener(displayKeyboard); 
} 

OnClickListener displayKeyboard = new OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      if(client == null) 
        return; 
      boolean on = ((ToggleButton) v).isChecked(); 
      if(on){ // show keyboard 
       System.out.println("Togglebutton is ON"); 
       keyboard.requestFocus(); 
       InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       mgr.showSoftInput(keyboard, InputMethodManager.SHOW_IMPLICIT); 
      } 
      else{ // hide keyboard 
       System.out.println("Togglebutton is OFF"); 
       InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       mgr.hideSoftInputFromWindow(keyboard.getWindowToken(), 0);   } 
     } 
    }; 

當我點擊鍵盤切換按鈕,我在logcat中看到它進入的if/else塊,但除此之外犯規在屏幕上顯示任何鍵盤。有人可以幫忙嗎?

回答

3

與您試圖集中你keyboard按鈕,並開始發送鍵盤事件給它的showSoftInput,但不可作爲焦點,讓它成爲可聚焦像這樣(在你的onCreate ):

keyboard.setFocusable(true); 
keyboard.setFocusableInTouchMode(true); 
+0

是的!就是這樣:)謝謝你:) :) – 2013-04-10 18:18:56

1

您可以試試這個(在UTILITY類中):

public static void hideSoftKeyboard(Activity activity) { 
      InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); 
      inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 
     } 

    public static void showSoftKeyboard(Activity activity, View focusedView) 
    { 
     InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); 
     inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); 
    } 
相關問題