当我们在Android提供的EditText中单击的时候,会自动的弹出软键盘,其实对于软键盘的控制我们可以通过InputMethodManager这个类来实现。我们需要控制软键盘的方式就是两种一个是像EditText那样当发生onClick事件的时候出现软键盘,还有就是当打开某个程序的时候自动的弹出软键盘。

  1. public class InputMethodManagerTest extends Activity implements OnClickListener{  
  2.     private Button button;  
  3.       
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         super.onCreate(savedInstanceState);  
  8.         LinearLayout layout=new LinearLayout(this);  
  9.         LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);  
  10.         button=new Button(this);  
  11.         button.setId(123);  
  12.         button.setText("Hello GaoMatrix");  
  13.         button.setOnClickListener(this);  
  14.         layout.addView(button, layoutParams);  
  15.         setContentView(layout);  
  16.           
  17.         /** 
  18.          * 用一个定时器控制当打开这个Activity的时候就出现软键盘 
  19.          */  
  20.         Timer timer=new Timer();  
  21.         timer.schedule(new TimerTask() {  
  22.             @Override  
  23.             public void run() {  
  24.                 InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
  25.                 inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
  26.             }  
  27.         }, 2000);  
  28.     }  
  29.     /** 
  30.      * 当单击事件的时候触发显示软键盘 
  31.      */  
  32.     @Override  
  33.     public void onClick(View v) {  
  34.         InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
  35.         inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
  36.     }  
  37. }  

 

这个InputMethodManager类里面的toggleSoftInput方法的API中的解释是:

This method toggles the input method window display. If the input window is already displayed, it gets hidden. If not the input window will be displayed.

这个方法在界面上切换输入法的功能,如果输入法出于现实状态,就将他隐藏,如果处于隐藏状态,就显示输入法。

而对于第二中方式进入Activity就自动显示软键盘,在一个定时器中,也就是在一个线程中执行,只不过是延迟2秒执行,原因是在onCreate函数中Android程序未将屏幕绘制完成。

posted on 2011-09-14 17:41  denniswang  阅读(5454)  评论(0编辑  收藏  举报