我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
我想在EditText被聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:
当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。
继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。
当前回答
根据这个答案,我使用了setSoftInputMode方法,并覆盖了DialogFragment中的这些方法:
@Override
public void onCancel(@NonNull DialogInterface dialog) {
super.onCancel(dialog);
requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}
@Override
public void onStart() {
super.onStart();
requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
@Override
public void onStop() {
super.onStop();
requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}
我也用这些方法创建了我自己的DialogFragment子类,所以当你创建另一个对话框并从这个类继承时,你会自动显示软键盘,而不需要任何其他编辑。希望对别人有用。
其他回答
对于片段,肯定它的工作:
displayName = (EditText) view.findViewById(R.id.displayName);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
要使键盘出现,请使用
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
这个方法比直接调用InputMethodManager更可靠。
要关闭它,使用
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
有时劳科德鲁格的答案并不管用。我是这样做的,经过了一些尝试和错误:
public static void showKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
public static void hideKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
EditText部分:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(getActivity());
} else {
showKeyboard(getActivity());
}
}
});
没有一个答案对我有用。这里有一个简单的方法。
searchEditText.setVisibility(View.VISIBLE);
final Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
searchEditText.requestFocus();
}
}, 400);
只是将requestFocus()方法延迟了400ms。
使用Xamarin,这对我来说是一个片段:
using Android.Views.InputMethods;
using Android.Content;
...
if ( _txtSearch.RequestFocus() ) {
var inputManager = (InputMethodManager) Activity.GetSystemService( Context.InputMethodService );
inputManager.ShowSoftInput( _txtSearch, ShowFlags.Implicit );
}