我已经将我的SDK更新到API 21,现在备份/向上图标是一个指向左边的黑色箭头。
我希望它是灰色的。我该怎么做呢?
例如,在Play Store中,箭头是白色的。
我这样做是为了设置一些样式。我已经使用@drawable/abc_ic_ab_back_mtrl_am_alpha作为homeAsUpIndicator。该可绘制对象是透明的(只有alpha),但箭头显示为黑色。我想知道我是否可以像在DrawerArrowStyle中那样设置颜色。或者如果唯一的解决方案是创建我的@drawable/grey_arrow并将其用于homeAsUpIndicator。
<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:actionBarStyle" tools:ignore="NewApi">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
<item name="android:homeAsUpIndicator" tools:ignore="NewApi">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
</style>
<!-- ActionBar style -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">
<item name="android:background">@color/actionbar_background</item>
<!-- Support library compatibility -->
<item name="background">@color/actionbar_background</item>
</style>
<!-- Style for the navigation drawer icon -->
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@color/actionbar_text</item>
</style>
到目前为止,我的解决方案是使用@drawable/abc_ic_ab_back_mtrl_am_alpha,它看起来是白色的,并使用照片编辑器将其涂成我想要的颜色。它的工作,虽然我更喜欢使用@color/actionbar_text像在DrawerArrowStyle。
另一个解决方案,可能为您的工作是不声明你的工具栏作为应用程序的操作栏(通过setActionBar或setSupportActionBar),并设置返回图标在你的onActivityCreated使用在本页上的另一个答案提到的代码
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationIcon(upArrow);
现在,当你按下后退按钮时,你将不会得到onOptionItemSelected回调。然而,你可以使用setNavigationOnClickListener注册。这就是我所做的:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().onBackPressed(); //or whatever you used to do on your onOptionItemSelected's android.R.id.home callback
}
});
我不确定它是否会工作,如果你与菜单项。
Carles的答案是正确的答案,但是像getDrawable(), getColor()这样的方法在我写这个答案的时候已经被弃用了。所以更新后的答案是
Drawable upArrow = ContextCompat.getDrawable(context, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
以下是一些其他的stackoverflow查询,我发现调用ContextCompat.getDrawable()类似于
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
和ContextCompat.getColor()类似
public static final int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompatApi23.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}
链接1:ContextCompat.getDrawable()
链接2:ContextCompat.getColor()