android - 如何为设计支持库的 NavigationView 设置样式?

标签 android material-design android-support-library androiddesignsupport navigationview

所以我使用Android Design Support Library 提供的NavigationView

enter image description here

我似乎找不到有关如何设置样式的示例。

到目前为止我有:

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:menu="@menu/drawer"
    app:itemTextColor="@color/black"
    app:itemIconTint="@color/black"/>

设置标题的样式很容易,因为它在自己的 xml 布局下,但正文是菜单资源文件而不是布局。

  • app:itemTextColor 改变文字颜色
  • app:itemIconTint 改变图标颜色
  • app:itemBackground 更改项目背景颜色

那么如何设置

  • 所选项目背景
  • 所选项目文本颜色
  • 所选项目图标色调

最佳答案

我已经回答了一个类似的问题 Here .

基本上你需要做的是,使用一个Color State List Resource。为此,首先在 color 目录(应该在 res 目录内)创建一个新的 xml(例如,drawer_item.xml)。如果你不'还没有一个名为 color 的目录,创建一个。

现在在 drawer_item.xml 里面做这样的事情

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="checked state color" android:state_checked= "true" />
    <item android:color="your default color" />
</selector>

对于itemBackground,一个单独的drawable 也需要放在drawable 文件夹中。名称与 drawer_item 相同。需要为 itemBackground 设置 android:drawable 属性而不是 android:color:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
       android:drawable="@drawable/shape_rectangle_checked"

        android:state_checked= "true" />
    <item android:drawable="@drawable/shape_rectangle" />

</selector>

文件shape_rectangle:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
<solid android:color="#ffffff" /> <!--white color -->
</shape>

文件shape_rectangle_checked:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
<solid android:color="#25aaf1" /> <!--blue color -->
</shape>

然后像这样在你的导航 View 中设置

app:itemIconTint="@color/drawer_item" //notice here
app:itemTextColor="@color/drawer_item" //and here
app:itemBackground="@drawable/drawer_item"//and here for changing the background color of the item which is checked

关于android - 如何为设计支持库的 NavigationView 设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097716/

相关文章:

android - 在当前主题中找不到样式 'cardView Style'

android - 使用自定义 Loader 时,不会在 ViewPager fragment 上调用 ​​onResume()

java - 如何在android中的网格布局的列之间显示垂直线

php - 使用 php 和 android 连接到 mysql 时出现 NullPointerException

android - 使用 appcompat v21 更改 actionOverflowButtonStyle

android - 在不继承 ActionBarActivity 的情况下添加操作栏

android - 如何在android中为gridview设置相等的列宽?

android - 默认发布 lint 与 gradle lint 任务

javascript - 需要在抽屉按钮上绑定(bind)onclick事件

css - Angular Material 和 layout-fill 最多可填充 100% 的屏幕,仅此而已