How to programmatically change the contents of a toolbar?

I am trying to programmatically change the contents of a toolbar.

The toolbar now has 1 ActionMenuView and 1 TextView: enter image description here

app_bar_transaction.xml:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_transaction"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#F6F6F6"
    app:popupTheme="@style/AppTheme.PopupOverlay" >

        <android.support.v7.widget.ActionMenuView
            android:id="@+id/menu_transaction"
            android:layout_width="wrap_content"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="left" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textColor="#5E5E5E"
            android:textStyle="bold"
            android:textSize="13sp"
            android:id="@+id/toolbar_title"
            android:gravity="center" />

</android.support.v7.widget.Toolbar>

I want to change the contents of the toolbar to this: enter image description here

How can I programmatically change the contents of a toolbar?

+4
source share
2 answers

Add LinearLayout to the other side of your toolbar like this.

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_transaction"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#F6F6F6"
app:popupTheme="@style/AppTheme.PopupOverlay" >

     <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>

and then in the Java file access this line, for example,

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

Now using this layoutToolbar add or remove any view from it

layoutToolbar.addView(); and layoutToolbar.removeView();
0
source

, toolbar.findViewById(R.id.view);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
ImageView imageInToolbar = (ImageView) toolbar.findViewById(R.id.myImageView);
0

Source: https://habr.com/ru/post/1628126/


All Articles