setSupportActionBar() throws Nullpointer exception

前端 未结 4 1237
执笔经年
执笔经年 2021-01-18 06:20

I am new to android and i was following following tutorial for Material Design Toolbar :

http://www.android4devs.com/2014/12/how-to-make-material-design-app.         


        
4条回答
  •  走了就别回头了
    2021-01-18 06:46

    You need to call setContentView BEFORE adding any Views such as the Toolbar.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         // <-- call this first
    
        toolbar = (Toolbar) findViewById(R.id.toolbar); // <-- setup views after
    
        setSupportActionBar(toolbar);
        setTitle("DDIT_Results");
    }
    

    Please see the Official Android Developers blog here: http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html

    Action Bar

    To use Toolbar as an Action Bar, first disable the decor-provided Action Bar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or its light variant).

    Second, create a Toolbar instance, usually via your layout XML:

    
    

    The height, width, background, and so on are totally up to you; these are just good examples. As Toolbar is just a ViewGroup, you can style and position it however you want.

    Then in your Activity or Fragment, set the Toolbar to act as your Action Bar:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blah);
    
        final Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
        setSupportActionBar(toolbar);
    }
    

    From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.

提交回复
热议问题