在片段中隐藏键盘屏幕



我想知道如何在活动中切换片段时隐藏键盘屏幕。

我有一个启动片段的活动。此片段有一个 TextInputEditText 视图,我可以在其中键入一些文本,当选择 TextInputEditText 视图时,键盘会自动显示。当我输入完文本后,我单击一个编程的"按钮",将我带到另一个片段。不幸的是,键盘屏幕仍然显示在这个新片段中,我希望它被隐藏/消失。

我已经在onCreateView(..(中尝试了以下内容,在setOnClickListener按钮内,在显示TextInputEditText视图的片段中。

片段:

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//send to the backend,when response come back, then insert
Fragment fragment = null;
Class fragmentClass = HashHomeFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("hash_message", "thisstorehaslotsofdiscounts");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.hash_container, fragment, "Home").commit();
//hide keyboard
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
});

但是当 android 进入片段时,键盘仍然存在——代码不起作用!

有人可以帮我弄清楚当我从一个片段移动到另一个片段时需要隐藏键盘的位置和代码吗?

public void hideKeyboard() {
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getContext().
getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
//hide keyboard
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("hash_message", "thisstorehaslotsofdiscounts");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.hash_container, fragment, "Home").commit();

倒车似乎可以解决问题。我忘记了当我调用最后一个片段管理器命令时,当前片段正在被销毁,当前视图没有指向我认为它是什么。 在当前视图完好无损的情况下隐藏键盘,然后切换片段更有意义!

也许您必须在隐藏键盘之前清除编辑文本的焦点。试试这个函数:

private void hideKeyboard(Context context) {
if (context == null || !(context instanceof Activity) || ((Activity) context).getCurrentFocus() == null) {
return;
}
View view = ((Activity) context).getCurrentFocus();
if (view != null) {
view.clearFocus();
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
import android.view.inputmethod.InputMethodManager;
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE); 
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);

我把它放在所有按钮的onClick(View v(事件之后。

单击按钮时键盘会隐藏。 希望这有帮助...

最新更新