在我的应用程序中,我想显示一个内容列表,并为用户提供使用软键盘过滤列表的能力。为此,我添加了一个按钮,该按钮应触发(隐藏/显示)软键盘进行过滤。我不想有一个可见的编辑文本控件,因为它会占用不必要的空间。而不是这样,我想在用户键入时显示一个显示过滤器查询的 toast,就像 ListView 的 'android:textFilterEnabled' 属性一样。据我了解,使用可用的 Android 组件没有明显的方法可以做到这一点。所以我尝试了以下方法:
1)创建一个包含不可见编辑文本和列表视图的布局:
<ListView android:id="@+id/main_list"
android:drawSelectorOnTop="false"
android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="5"
/>
2)添加按钮作为弹出窗口并在单击时调用 InputMethodManager 以切换软输入(在 onCreate 中调用):
private void initButton() {
Button buttonView = (Button) getLayoutInflater().inflate(R.layout.keyboard_button, null);
buttonView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final View target = findViewById(R.id.filterbox);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// this does not work...
// imm.toggleSoftInputFromWindow(target.getWindowToken(), InputMethodManager.SHOW_FORCED, 0);
// ... so need to track this in an instance variable - which sucks
if (imeShowing) {
imm.hideSoftInputFromWindow(target.getWindowToken(), 0);
imeShowing = false;
} else {
// check that the filterbox got focus
Preconditions.checkState(target.requestFocusFromTouch());
Preconditions.checkState(target.hasWindowFocus());
Preconditions.checkState(target.hasFocus());
imm.showSoftInput(target, 0);
imeShowing = true;
}
}
});
buttonPopup = new PopupWindow(buttonView);
// ... code to display the button as a small popup
}
正如代码示例中提到的,“显而易见”的方法(调用 toggleSoftInput)不起作用,所以我不得不恢复到这个丑陋的 if-else。然而,这是次要问题。主要问题是,当我在模拟器中运行它时,软键盘显示正确,但是一旦我开始输入,系统就会启动谷歌搜索活动的意图!并且键入的字符会出现在作为结果显示的 Google 搜索框中。更奇怪的是,这只会在我部署和运行应用程序后第一次输入时发生。即,如果我从 Google 搜索框返回我的应用程序,一切都会按预期工作(不会重定向到搜索框)。在显示显示之前,我确保不可见的编辑文本获得焦点,所以它应该是软键盘的目标,对吧?
有谁知道这里发生了什么?