我在按钮点击时实现隐藏键盘时出错,有人知道如何解决这个问题吗? 实际上是getSystemService和getWindowsToken
中的代码错误@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calculator, container, false);
Button hitung = (Button) rootView.findViewById(R.id.hitung);
final EditText height = (EditText)rootView.findViewById(R.id.height);
final EditText weight = (EditText)rootView.findViewById(R.id.weight);
InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditText.getWindowToken(), 0);
final TextView result = (TextView)rootView.findViewById(R.id.result);
final TextView finalresult = (TextView)rootView.findViewById(R.id.finalresult);
finalresult.setMovementMethod(new ScrollingMovementMethod());
hitung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
..........
}
答案 0 :(得分:6)
您正在使用Fragment
,请写上getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)
相同的原因:
活动扩展上下文,片段不扩展。因此,您首先需要获得对包含片段的活动的引用
修改
您可以使用的评论中提到的其他错误
getView().getWindowToken()
并且应该在button's
onClick()
方法中调用隐藏方法,例如
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
答案 1 :(得分:6)
使用此,
public static void hideKeyboard(Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(((Activity) mContext).getWindow()
.getCurrentFocus().getWindowToken(), 0);
}
答案 2 :(得分:1)
使用下面的代码
try {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
if(net.one97.paytm.common.utility.CJRAppCommonUtility.isDebug) e.printStackTrace();
}
答案 3 :(得分:1)
// hide keyboard
public static void hideSoftKeyboard(Context context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
if(inputMethodManager != null && inputMethodManager.isActive())
{
//inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
//InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
答案 4 :(得分:1)
hitung.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
答案 5 :(得分:0)
在 Koltin 中,您可以这样做。
fun View.hideKeyboard() {
val imm = getSystemService(context,
InputMethodManager::class.java) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
只要您想在单击时隐藏键盘,随时可以从任何视图调用此扩展功能!