Nullpointerexception thrown when trying to findViewById

前端 未结 3 1031
[愿得一人]
[愿得一人] 2020-12-07 06:15

I have the following Activity:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    supe         


        
3条回答
  •  情歌与酒
    2020-12-07 06:59

    Try to implement your onCreateView(...) in Fragment like

    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
     Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.fragment_main, container,
      false);
    
     View something = rootView.findViewById(R.id.something);
     something.setOnClickListener(new View.OnClickListener() { ... });
    
    return rootView;
    }
    

    The Button is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

提交回复
热议问题