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. }
复制代码
这个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程序未将屏幕绘制完成。
当然我们还可以单独控制软键盘的显示和隐藏
1. //显示
2. InputMethodManager imm =
(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
3. imm.showSoftInput(view, 0); 4.
5. //隐藏
6. imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
复制代码
上述代码中的view是比如Button点击时事件的那个View,或者是Activity整个布局之类的Layout(经傻蛋测试可以正常运行)
其他关于键盘的控制还有两个经常用到:
1. editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); //点击EditText时,不会弹出一个全屏输入窗口
2.editText.setInputType(InputType.TYPE_NULL); //点击EditText时,屏蔽软键盘
因篇幅问题不能全部显示,请点此查看更多更全内容