0

How to add toolbar programmatically to LinearLayout. I tried the below code, but it is not working.

My class extends FragmentActivity.

Toolbar toolbar = new Toolbar(this);
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
        Toolbar.LayoutParams.MATCH_PARENT,
        R.attr.actionBarSize
);
toolbar.setLayoutParams(toolBarParams);
toolbar.setBackgroundColor(Color.BLUE);
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay);
toolbar.setVisibility(View.VISIBLE);
LinearLayout ll = (LinearLayout) findViewById(R.id.activity_search);
ll.addView(toolbar);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Nikhil
  • 167
  • 3
  • 16
  • `R.attr.actionBarSize` is a resource identifier for an attribute. It's not the actual size. You would need to do something like is shown in [this post](http://stackoverflow.com/a/7913610) to get that. Beyond that, how exactly is it not working? – Mike M. Feb 25 '17 at 17:49
  • Even though if I change R.attr.actionbarSize to 100, it is not showing any thing. – Nikhil Feb 25 '17 at 17:56
  • 1
    OK, some other possible issues: The `Toolbar` is going into a `LinearLayout`, so it needs `LinearLayout.LayoutParams`, not `Toolbar.LayoutParams`. Make sure the `LinearLayout` has the correct orientation for what you expect. Also make sure that any existing child `View`s in the `LinearLayout` aren't already filling it, and pushing the `Toolbar` outside of it. If you're wanting to insert the `Toolbar` before other child `View`s, use the `addView(View, int)` method to add it at a specific index. – Mike M. Feb 25 '17 at 18:02
  • 1
    Thanks Mike, its working now after changing it to LinearLayout.LayoutParams – Nikhil Feb 25 '17 at 18:07

1 Answers1

2

Below code is working after modification:

        Toolbar toolbar = new Toolbar(this);
        LinearLayout.LayoutParams toolBarParams = new LinearLayout.LayoutParams(
                Toolbar.LayoutParams.MATCH_PARENT,
                150
        );
        toolbar.setLayoutParams(toolBarParams);
        toolbar.setBackgroundColor(Color.BLUE);
        toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay);
        toolbar.setVisibility(View.VISIBLE);


        LinearLayout ll = (LinearLayout) findViewById(R.id.activity_search);
        ll.addView(toolbar, 0);
Nikhil
  • 167
  • 3
  • 16