Changing the Action bar icon

2019-01-19 01:45发布

I'm currently implementing theme support for my application and a part of it is changing the action bar app icon. I want to use a dark icon when Holo Light is selected. Everything is done in the method except for the part where the action bar app icon is set. The code that im trying to use is:

getActionBar();
ActionBar.setIcon(R.drawable.my_icon);

"There is no such reference avavible here" is the error that i'm getting. How should this be done correctly?

BTW my minSdkVersion is 14 so no action bar sherlock stuff.

7条回答
Luminary・发光体
2楼-- · 2019-01-19 01:54
getActionBar();

You're throwing the action bar away right there. getActionBar() returns an instance of ActionBar, which you then need to call setIcon() on. Like so:

ActionBar actionBar = getActionBar();
actionBar.setIcon(R.drawable.my_icon);
查看更多
SAY GOODBYE
3楼-- · 2019-01-19 02:02

You need to add the drawable that you want to reference into your drawable/ folder under res/.

edit: In your Android installation folder there are a lot of stock images to use. You can probably find it there.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-19 02:09

The existing answer is very correct. There is, however, also an alternative. A minimal approach would be to use

getActionBar().setIcon(R.drawable.my_icon);

Gets your job done right away. :)

Technical Details: Since getActionBar() by default returns an object, you can directly manipulate it without having to receive it in an in-scope object explicitly.

查看更多
仙女界的扛把子
5楼-- · 2019-01-19 02:11

Try this

    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null)
    getSupportActionBar().setIcon(R.drawable.your_icon);
查看更多
【Aperson】
6楼-- · 2019-01-19 02:14

I am using this for my use , and it's working for me. Hope this help all

actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.icon);
查看更多
我只想做你的唯一
7楼-- · 2019-01-19 02:16

Calling to setIcon wasn't enough for me.

Before that, I had to switch the display from activity logo to activity icon:

actionBar.setDisplayUseLogoEnabled(false);

For the differences between activity icon and logo see Android icon vs logo.

查看更多
登录 后发表回答