Vlad Vlad - 13 days ago 7
Android Question

How to programmatically instantiate a Toolbar in Android?

I've looked all over the Internet but for some reason couldn't find anyone mention how you can instantiate a toolbar 100% programmatically.

Most of them talk about using the XML. I already know how to do that. I want to know how to use only code to instantiate it.

I tried doing something like:

Toolbar toolbar = new Toolbar(this);
toolbar.setTitle("This is a title");
setSupportActionBar(toolbar);


but it doesn't seem to show up. This is strange that I can't find a single article discussing this online. Maybe it's not possible? Would appreciate guidance. Thank you!

Answer

Create Toolbar Programatically this way

Toolbar toolbar = new Toolbar(this);
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
                Toolbar.LayoutParams.MATCH_PARENT,
                R.attr.actionBarSize
        );
toolbar.setLayoutParams(toolBarParams);

and then attach to your layout.