onCreateView() - 无法对非静态方法进行静态引用

时间:2015-02-15 12:39:20

标签: java android android-layout android-activity android-fragments

我想在字段上输入一些文字后关闭软键盘。这是我在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;
        }
    }
}

2 个答案:

答案 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);