【问题标题】:Is it possible to set navigation item background color dynamically in android?是否可以在android中动态设置导航项背景颜色?
【发布时间】:2017-05-30 09:40:05
【问题描述】:

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

导航视图

<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>

提前致谢

【问题讨论】:

标签: android navigation navigation-drawer


【解决方案1】:

navigationView.setItemBackground(Color.parseColor("#000"));

【讨论】:

    【解决方案2】:

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

    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);
    

    【讨论】:

    • 谢谢@Mr。兔子,但我想设置项目背景颜色,即 app:itemBackground="@drawable/drawer_selector"
    • 您是从服务器获取图像还是仅获取颜色?并从这些颜色中创建可绘制选择器或颜色选择器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多