Error: Non-static method 'findViewById(int)' cannot be referenced from a static context

后端 未结 5 1792
天命终不由人
天命终不由人 2020-12-31 05:27

I am using Android Studio (Beta), and while using this java code in \'onCreateView()\', I get an error.

ListView listView = (ListView) findViewById(R.id.some         


        
相关标签:
5条回答
  • 2020-12-31 06:10

    onCreateView() shouldn't be a static method (I'm assuming you are defining it within an Activity class), so you must be doing something wrong.

    0 讨论(0)
  • 2020-12-31 06:19

    Inside Activity class

     static ListView listView;
     listView = (ListView) this.findViewById(R.id.someListView);
    

    OR

    to create inside fragmentClass(static)

      static ListView listView;
      listView = (ListView) getActivity().findViewById(R.id.someListView);
    
    0 讨论(0)
  • 2020-12-31 06:26

    If you are using it in an static AsyncTask, or any other class, you can pass the activity as a parameter to a method or constructor, for example:

    activity onCreate:

    //Pass activity variable (this)
    new Main2Activity.MyTask().execute(this);
    

    class inside activity:

    private static class MyTask extends AsyncTask<Object, Void, String> {
    
            Main2Activity activity;
    
            @Override
            protected String doInBackground(Object... params) {
                activity = (Main2Activity)params[0];
                ....
            }
    
            @Override
            protected void onPostExecute(String str) {
                // Use parameter activity passed to class
                WebView webView = activity.findViewById(R.id.web_view);
                webView.loadData(str, "text/html; charset=UTF-8", null);
            }
    
    0 讨论(0)
  • 2020-12-31 06:30

    Assuming you have a static fragment inner class inside an activity: you're trying to call the activity's findViewById() which you cannot in a static inner class that doesn't hold a reference to the parent.

    In onCreateView() you need to call it on the root view you just inflated, e.g.

     ListView listView = (ListView) rootView.findViewById(R.id.someListView);
    
    0 讨论(0)
  • 2020-12-31 06:33
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_layout, container, false);
        ListView listView = (ListView) view.findViewById(R.id.listviewID);
        context = getActivity();
        return view;
    }
    

    You can implement this now... Use view variable to access xml ui things in oncreateView and getActivity().findViewById(...) to access other then onCreateView() Method.

    0 讨论(0)
提交回复
热议问题