我更希望Android使用自己默认的EditText行为而不是构建自己的行为,但似乎每个人(在那些线程中)都接受了在对话框中EditText的默认行为只是给出光标而没有键盘。为什么会这样呢?
记录一下,这些解决方法似乎都不适用于我——我能做到的最接近的方法是强制一个键盘出现在对话框下面(使用InputMethodManager.toggleSoftKeyboard(*))。我的特定配置是API15,在AlertDialog中的ListView的页脚上显示EditText。EditText android:focusable="true"已设置,并且onFocusChangeListener正在接收焦点事件。
编辑:
根据要求,这里是我正在使用的特定代码片段。我不会费心去整个布局,但在这个特定的应用程序中,EditText是响应于对话框上的按钮(类似于操作视图)而出现的。它包含在一个默认可见性为“gone”的RelativeLayout中:
<RelativeLayout
android:id="@+id/relLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="gone"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp">
<ImageButton
android:id="@+id/cancelBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@color/transparent"
android:src="@drawable/cancelButton"
android:layout_margin="5dp"/>
<ImageButton
android:id="@+id/okBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/cancelBut"
android:background="@color/transparent"
android:src="@drawable/okButton"
android:layout_margin="5dp" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:focusable="true"
android:layout_toLeftOf="@id/okBut"/>
</RelativeLayout>
构建此代码将相对布局的可见性设置为“Visible”(并隐藏其他UI元素)。根据我对EditText的经验,这应该足以在EditText获得焦点时拉起键盘。然而,由于某种原因,情况并非如此。我可以设置以下onFocusChangeListener:
edit_text.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// For whatever reason we need to request a soft keyboard.
InputMethodManager imm = (InputMethodManager)dlg.getWindow().getContext().getSystemService(_Context.INPUT_METHOD_SERVICE);
if(hasFocus)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Log.v("DialogProblem", "Focus requested, " + (hasFocus?"has focus.":"doesn't have focus."));
}
}
});
使用这个配置,当我第一次进入EditText时,onFocusChangedListener会触发,并生成一个日志,通常看起来像这样:
Focus requested, has focus.
Focus requested, doesn't have focus.
Focus requested, has focus.
键盘出现后又消失了,可能是因为我切换了两次,但即使我确保它保持打开状态,它仍然在对话框窗口的后面(在一个灰色区域中),没有办法在不关闭对话框的情况下访问它。
话虽如此,我想强调的是,尽管我可能能够让这个解决方法起作用,但我主要关心为什么EditText一开始就没有触发,以及为什么这似乎是如此普遍的问题!