我想在字段上输入一些文字后关闭软键盘。这是我在Fragment的onCreateView()上的代码。但是,我收到以下错误:
Cannot make a static reference to the non-static method getWindow() from the type Activity
Cannot make a static reference to the non-static method getSystemService(String) from the type Activity
有什么想法吗?
public class SignInActivity extends ActionBarActivity {
[...]
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_in,
container, false);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
EditText phone =
(EditText)getView().findViewById(R.id.input_field);
phone.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(((TextView) v.getWindowToken()).getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
}
});
return rootView;
}
}
}
答案 0 :(得分:1)
需要
getActivity().getWindow()
和
getActivity().getSystemService()
您的代码中还有另一个错误。而不是
EditText phone =
(EditText)getView().findViewById(R.id.input_field);
它需要
EditText phone =
(EditText)rootView.findViewById(R.id.input_field);
答案 1 :(得分:1)
这两种方法需要Context
片段dosnt保持。
替换
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
与
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
和
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
与
InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);