当我们在Android提供的EditText中单击的时候,会自动的弹出软键盘,其实对于软键盘的控制我们可以通过InputMethodManager这个类来实现。我们需要控制软键盘的方式就是两种一个是像EditText那样当发生onClick事件的时候出现软键盘,还有就是当打开某个程序的时候自动的弹出软键盘。
public class InputMethodManagerTest extends Activity implements OnClickListener{
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LinearLayout layout=new LinearLayout(this);
LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
button=new Button(this);
button.setId(123);
button.setText("Hello GaoMatrix");
button.setOnClickListener(this);
layout.addView(button, layoutParams);
setContentView(layout);
/**
* 用一个定时器控制当打开这个Activity的时候就出现软键盘
*/
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 2000);
}
/**
* 当单击事件的时候触发显示软键盘
*/
@Override
public void onClick(View v) {
InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
这个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程序未将屏幕绘制完成。
本文介绍如何使用InputMethodManager类在Android应用中控制软键盘的显示与隐藏,包括自动在Activity启动时显示软键盘的方法。
2625

被折叠的 条评论
为什么被折叠?



