Adneal的回答很好,我一直在使用它,直到最近。但是,我想让我的应用程序使用Material Design,因此需要使用Theme.AppCompat.*
样式和android.support.v7.widget.Toolbar
。
是的,它停止工作了,我试图通过将Your.Theme
的父级设置为@style/Widget.AppCompat.ActionButton.Overflow
来修复它。通过正确设置contentDescription
,它可以正常工作,但是在转换为ImageButton
时失败了。原来在最新的(version 23) android.support.v7
类中,OverflowMenuButton
扩展自AppCompatImageView
。更改强制转换类就足以使其在运行Lollipop的Nexus 5上与Toolbar一起工作。
然后我在装有KitKat的Galaxy S4上运行它,无论我尝试什么,都无法将overflow的contentDescription
设置为我的自定义值。但是在AppCompat styles中,我发现它已经有默认值:
<item name="android:contentDescription">@string/abc_action_menu_overflow_description</item>
那么为什么不使用它呢?此外,根据Hannes的想法(在评论中),我实现了监听器,以消除postDelayed
中的一些随机延迟时间。由于溢出图标已经在AppCompat库中,因此我也会使用它 - 我正在应用颜色过滤器,因此我不需要自己的任何图标资源。
我的代码基于Adneal的Android Lollipop改进工作:
public static void setOverflowButtonColor(final Activity activity) {
final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
final ArrayList<View> outViews = new ArrayList<View>();
decorView.findViewsWithText(outViews, overflowDescription,
View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
if (outViews.isEmpty()) {
return;
}
AppCompatImageView overflow=(AppCompatImageView) outViews.get(0);
overflow.setColorFilter(Color.CYAN);
removeOnGlobalLayoutListener(decorView,this);
}
});
}
根据另一个StackOverflow答案:
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
}
else {
v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
当然,你可以使用自己的颜色而不是“Color.CYAN” - “activity.getResources().getColor(R.color.black);”
编辑:
添加了对最新的AppCompat库(23)的支持,它使用AppCompatImageView
对于AppCompat 22,您应该将溢出按钮转换为TintImageView