可以在android中动态设置导航项背景颜色吗?

时间:2017-05-30 09:40:05

标签: android navigation navigation-drawer

是否可以动态设置导航项背景颜色

导航视图

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:background="@color/white"
        app:itemIconTint="@color/navigation_color"
        app:itemTextColor="@color/navigation_color"
        app:itemBackground="@drawable/drawer_selector"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/activity_home_drawer"
        />

drawable_selector

<?xml version="1.0" encoding="utf-8"?>
<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>

提前致谢

2 个答案:

答案 0 :(得分:0)

在您的活动中,只需使用以下代码:

int customNormalColorFromServer = Color.WHITE; // Replace value with your color retreiving logic
int customFocusedColorFromServer = Color.GRAY; // Replace value with your color retreiving logic

ColorStateList colorStateList = new ColorStateList(new int[][] {
                    new int[] {android.R.attr.state_selected},
                    new int[] {-android.R.attr.state_selected}
                },
                new int[] {customFocusedColorFromServer, customNormalColorFromServer}
    );

NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(colorStateList);

答案 1 :(得分:0)

navigationView.setItemBackground(Color.parseColor(&#34;#000&#34));