Search code examples
androidandroid-toolbar

How to programmatically add elements to toolbar


I'm currently making an app with backwards support for toolbars, and thus I have this file

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>

I then programatically add it in to the views by doing something like:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

However, I want to be able to add custom views into the Toolbar, such as EditText and TextView's without hard-coding them into the toolbar.xml above.

Is there any way to do this? It might be worth noting that I'm using the V7 support library.

Thanks, Liam


Solution

  • Just give a try to the following

    Step 1 : Add LinearLayout to the toolbar in xml file

    <android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
        <LinearLayout
               android:id=@+id/toolbar_item_container
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:orientation="horizontal" />
    </android.support.v7.widget.Toolbar>
    

    Step 2 : Get this LinearLayout in code

    Toolbar mToolbar = (Toolbar)findViewById(R.id.toolbar_transaction);
    LinearLayout layoutToolbar = (LinearLayout)
                      mToolbar.findViewById(R.id.toolbar_item_container);
    

    Step3 : Add and Remove view to this LinearLayout using following code

    layoutToolbar.addView();
    layoutToolbar.removeView();
    

    This can be done without LinearLayout also, by directly adding and removing elements from Toolbar. You can try both the ways.

    Hope it'll help.