我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
当前回答
要强制显示软键盘,可以使用
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
为了移除EditText上的焦点,你需要一个虚拟视图来抓取焦点。
关闭它,你可以使用
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
这适用于在对话框中使用它
public void showKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void closeKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
其他回答
我发现了一个奇怪的行为,因为在我的一个应用程序中,软键盘在进入活动时自动显示(onCreate中有editText.requestFocus())。
进一步挖掘,我发现这是因为布局周围有一个ScrollView。如果我删除ScrollView,行为如原始问题声明中所述:只有在单击已经聚焦的editText时,软键盘才会显示出来。
如果这对你不起作用,试着加入一个ScrollView——无论如何这是无害的。
使用Xamarin,这对我来说是一个片段:
using Android.Views.InputMethods;
using Android.Content;
...
if ( _txtSearch.RequestFocus() ) {
var inputManager = (InputMethodManager) Activity.GetSystemService( Context.InputMethodService );
inputManager.ShowSoftInput( _txtSearch, ShowFlags.Implicit );
}
这对我很管用。你也可以尝试用这个来显示键盘:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
我用定时器。键盘可以显示编辑文本聚焦。
edittext = (EditText) findViewById(R.id.edittext );
edittext.requestFocus();
edittext.setFocusableInTouchMode(true);
if (edittext.requestFocus()) {
final Thread timer = new Thread() {
public void run() {
try{
sleep(500);
InputMethodManager imm =(InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
imm.showSoftInput(edittext, SHOW_IMPLICIT);
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.start();
我使用这个扩展函数来显示Kotlin的键盘。
fun EditText.requestFocusWithKeyboard() {
post {
dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0))
dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0))
setSelection(length())
}
}
你可以把它叫做:
editText.requestFocusWithKeyboard()
除了非常方便之外:
您不必担心在所有可能的情况下关闭它,例如当您使用InputMethodManager.SHOW_FORCED导航返回时。 除了请求焦点,它还设置选择(光标到文本末尾)。