【发布时间】:2012-02-20 11:14:07
【问题描述】:
我在安卓上的虚拟键盘上苦苦挣扎。问题是我无法可靠地显示/隐藏它。
这是拒绝在我测试的三台设备(ZTE Blade、Galaxy Nexus 和 Acer A500)上打开键盘的代码。
我可以隐藏键盘,也可以切换它,但我不能显示它。我可以使用切换来显示/隐藏它,但它不够可靠(因为似乎无法查看键盘是否显示)。
完整代码,看看能不能实现:
package com.test.keyboardtest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class KeyboardTestActivity extends Activity {
LinearLayout myLayout = null;
TextView myView = null;
Button toggleButton = null;
Button showButton = null;
Button hideButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myLayout = new LinearLayout(this);
myView = new TextView(this);
showButton = new Button(this);
hideButton = new Button(this);
toggleButton = new Button(this);
myLayout.setOrientation(LinearLayout.VERTICAL);
myLayout.addView(myView);
myLayout.addView(showButton);
myLayout.addView(hideButton);
myLayout.addView(toggleButton);
showButton.setText("Show Keyboard");
showButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(myView, 0 );
}
});
hideButton.setText("Hide Keyboard");
hideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(myView.getWindowToken(), 0 );
}
});
toggleButton.setText("Toggle Keyboard");
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.toggleSoftInput(0,0);
}
});
this.setContentView(myLayout);
}
}
【问题讨论】:
-
其实检测键盘是否可见并不难:stackoverflow.com/questions/2150078/…
-
好吧,您建议的代码并不总是有效。这取决于许多因素。例如,在窗口上设置 FLAG_LAYOUT_NO_LIMITS-flag 会阻止我获得 onGlobalLayout-events。我可以在需要时启用/禁用该标志,但它只能从 UI 线程调用。
-
嗯,在*范围内 范围 的 信息我> 你 提供,它会工作。你可能会在键盘上跳来跳去,同时发出狂野的猴子尖叫声,这也可能会导致问题。