chr*_*ine 63 android navigation-drawer material-design navigationview androiddesignsupport
新设计支持库中的新NavigationView非常棒.
他们使用" 菜单项 "来显示选项.
但我怎么能显示计数器到正确的菜单项?
就像在这张图片中:

或者像GMail应用程序一样.
Ale*_*kov 126
从appcompat-v7的第23版开始NavigationView,它支持动作视图,因此很容易自己实现计数器.
创建计数器布局,即menu_counter.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
Run Code Online (Sandbox Code Playgroud)在抽屉菜单xml中引用它,即menu/drawer.xml:
<item
...
app:actionLayout="@layout/menu_counter" />
Run Code Online (Sandbox Code Playgroud)请注意,您应该使用app命名空间,不要尝试使用android.
或者,您可以使用MenuItem.setActionView()方法手动设置操作视图.
查找菜单项并设置计数器:
private void setMenuCounter(@IdRes int itemId, int count) {
TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView();
view.setText(count > 0 ? String.valueOf(count) : null);
}
Run Code Online (Sandbox Code Playgroud)请注意,如果必须支持Android 2.x版本,则需要使用MenuItemCompat.
我的解决方法是将具有不同背景的SpannableString作为MenuItem的新标题传递.
我知道这不是最好的解决方案,它不是正确对齐的,但它可以很好地用作计数器.像这样的东西:
NavigationView navigation = (NavigationView)findViewById(R.id.navigation);
Menu menuNav = navigation.getMenu();
MenuItem element = menuNav.findItem(R.id.item5);
String before = element.getTitle().toString();
String counter = Integer.toString(5);
String s = before + " "+counter+" ";
SpannableString sColored = new SpannableString( s );
sColored.setSpan(new BackgroundColorSpan( Color.GRAY ), s.length()-(counter.length()+2), s.length(), 0);
sColored.setSpan(new ForegroundColorSpan( Color.WHITE ), s.length()-(counter.length()+2), s.length(), 0);
element.setTitle(sColored);
Run Code Online (Sandbox Code Playgroud)
为了改进计数器,你可以在这里找到一个圆角设置好的答案
例:
查看源代码NavigationView,他们目前不支持菜单项的任何自定义呈现(请参阅NavigationMenuPresenter和NavigationMenuAdapter).希望他们尽快公开更多功能,因为我想在菜单项上设置自定义字体,但我不能不使用反射.
| 归档时间: |
|
| 查看次数: |
25509 次 |
| 最近记录: |