Search code examples
androidandroid-toolbar

How can I change my custom toolbar icon dynamically


In my application I'm using toolbar which having imageview in it. I need to change that imageview dynamically .

Here is my toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/white"
    android:id="@+id/toolbar"
    app:theme="@style/ToolbarStyle" >

    <ImageView
        android:id="@+id/actionBarImage"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginRight="65dp"
        android:src="@drawable/forewarn"/>

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

Here is toolbar declaration in activity:

final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final ImageView imageInToolbar = (ImageView) toolbar.findViewById(R.id.actionBarImage);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();

        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//            getSupportActionBar().setLogo(R.drawable.abc);
        }

here is my actual toolbar :

here is my actual toolbar image :

my required toolbar with dynamic change of imageview :

toolbar with dynamic change


Solution

  • As per my comment Try this :

    final ImageView imageInToolbar = (ImageView) toolbar.findViewById(R.id.actionBarImage);
    setSupportActionBar(toolbar);
    imageInToolbar.setImageDrawable(ContextCompat.getDrawable(th‌​is, R.drawable.abc));
    

    For loading image from server :

    For Glide use :

    Glide.with(this)
         .load(url) 
         .into(imageInToolbar);
    

    In gradle : compile 'com.github.bumptech.glide:glide:3.8.0'

    For picasso use :

    Picasso.with(this).load(url).into(imageInToolbar);