在我的对话框 fragment 中,我可以使用
显示键盘getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);
但我无法在 dismiss
上隐藏它。
我试过了
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
和
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
两者都不起作用。
我还尝试使用
显示和隐藏键盘InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(0, 0);
和
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
但是这些无法显示或隐藏键盘。
public static class MyDialogFragment extends DialogFragment
{
@Nullable @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_input_dialog, container, false);
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState)
{
super.onViewCreated(v, savedInstanceState);
final EditText editText = (EditText)v.findViewById(R.id.input);
// this line below is able to show the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Button add = (Button)v.findViewById(R.id.add_btn);
add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// other code not shown
dismiss();
}
});
Button cancel = (Button)v.findViewById(R.id.cancel_btn);
cancelButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dismiss();
}
});
}
@Override
public void onDismiss(DialogInterface dialog)
{
//this line below does NOT work, it does not hide the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onDismiss(dialog);
}
}
注意:我已阅读这些 stackoverflow 帖子并尝试了建议的解决方案但无济于事:
最佳答案
解决方案结果是以下组合。在 DialogFragment 中显示键盘:
@Override
public void onResume()
{
super.onResume();
editText.post(new Runnable()
{
@Override
public void run()
{
editText.requestFocus();
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
}
要隐藏它,使用@Shekhar 上面的解决方案
@Override
public void onDismiss(DialogInterface dialog)
{
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive())
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
super.onDismiss(dialog);
}
关于android - 隐藏以在 DialogFragment 中显示和隐藏键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41725817/