Android - ResourcesNotFoundException when trying t

2019-05-31 14:21发布

问题:

I am changing my Action Bar icon to CircleImageView that shows profile picture:

CircleImageView actionBarIcon_Profile = new CircleImageView(this);
actionBarIcon_Profile.setImageDrawable(getResources().getDrawable(R.drawable.my_picture));
actionBarIcon_Profile.setLayoutParams(new LayoutParams(48, 48));
actionBarIcon_Profile.setId(R.id.actionBarIcon_Profile);

getActionBar().setIcon(R.id.actionBarIcon_Profile);

The ids are kept in ids.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="actionBarIcon_Profile"/>
</resources>

I get ResourcesNotFoundException. Any help will be appreciated.

回答1:

setIcon is expecting to receive an id of a resource. That id actionBarIcon_Profile is just an unique id you're creating that has no resource associated with it. That's why you're getting ResourcesNotFoundException.

You can set a drawable to your actionbar's setIcon method. Not an imageview. You need to create a circular drawable instead of a circular imageView.