How can I change my custom toolbar icon dynamically

随声附和 提交于 2019-12-20 07:44:01

问题


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 :

my required toolbar with dynamic change of imageview :


回答1:


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



回答2:


Try this

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });


来源:https://stackoverflow.com/questions/48018662/how-can-i-change-my-custom-toolbar-icon-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!