How to know if an Android actionbar's action i

2019-04-09 03:52发布

I have a split action bar, where the top bar is dark and the bottom bar (split) is light.

Consequently, I'd like to show a contrast action icons: Light icons in the top dark bar and dark icons in the bottom light bar.

The problem is knowing if the actions should be painted on the top or bottom bar. How can I know that?

Another option is to know whether the action bar is currently split. How do I know that?

Thanks.

2条回答
干净又极端
2楼-- · 2019-04-09 04:29

It depends on the library you are using.

For the new Appcompat : check the value of R.bool.abc_split_action_bar_is_narrow:

boolean split = getResources().getBoolean(R.bool.abc_split_action_bar_is_narrow);

For ActionBarShelock : import the ResourcesCompat class from the library and call :

boolean split = ResourcesCompat.getResources_getBoolean(this, R.bool.abs__split_action_bar_is_narrow);

If you don't use any library then you can go with Ahmad's answer but only if you don't use a library. This is because they use different values. The android framework seems to split the bar if the width is lower than 400dp, but for appcompat and ABS it's 480dp.

查看更多
小情绪 Triste *
3楼-- · 2019-04-09 04:32

Simple. You use boolean values. By default you'll have a split ActionBar if the screen width is smaller than 400dp. So in your values folder you can put:

/values/bools.xml:

<resources>
    <bool name="split_action_bar">true</bool>
</resources>

and in your values-sw400dp you put the following.

/values-sw400dp/bools.xml:

<resources>
    <bool name="split_action_bar">false</bool>
</resources>

Now you can set your icon based on that value:

boolean isActionBarSplitted = getResources().getBoolean(R.bool.split_action_bar);
if(isActionBarSplitted){
      // set light icon
}
else{
     // set dark icon
}

Edit:

Actually forget what I wrote, you don't need to create your own boolean value to check it. There is already one declared(which is the one the ActionBar uses to determine if it is a handset device or a tablet). If you're targeting Android HC+, then you can access the default ActionBars value: android.R.bool.split_action_bar_is_narrow, if you are using ActionBarSherlock: R.bool.abs_split_action_bar_is_narrow. Found here for the default ActionBar, here your ABS.

查看更多
登录 后发表回答