如何更改导航抽屉中所选项目的背景颜色

10
我正在开发应用中的导航抽屉功能。我已将我的导航抽屉背景设置为 #000000(黑色)。每当我选择任何项目时,文本颜色从 #E44F50(胡萝卜红)更改为黑色,但是我无法更改所选项目的背景颜色。我想要的是将所选项目的背景颜色从黑色更改为胡萝卜红。

这是我的应用的Github链接-

https://github.com/manmeet-22/NewsSnips-app.git

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/colorPrimary"
        app:headerLayout="@layout/header"
        app:itemIconTint="@drawable/drawer_item" //changing text color 
        app:itemTextAppearance="@style/TextAppearance20"
        app:itemTextColor="@color/drawer_item"
        app:itemBackground="@drawable/drawer_selected_item" //trying to change backgroundcolor the same way
        app:menu="@menu/drawer"
        tools:context="com.androidexample.newssnips.app.NavigationDrawerFragment"/>
</android.support.v4.widget.DrawerLayout>

我试图像更改文本一样更改背景颜色,但我的应用程序崩溃了。

这是我的drawer_selected_item.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorAccent" android:state_selected="true"/>
    <item android:color="@android:color/transparent"/>
</selector>

这里是我的drawer_item.xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/colorPrimary" android:state_checked="true" />
        <item android:color="@color/colorAccent" />
</selector>

这是我的MainActivity.java文件:

navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setItemIconTintList(null);
        Menu menu = navigationView.getMenu();

        //For chnaging the textColor and textSize of group's Name ie. Category
        MenuItem categoryName= menu.findItem(R.id.categoryGroup);
        SpannableString s = new SpannableString(categoryName.getTitle());
        s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance25), 0, s.length(), 0);

        //For changing the Text of action bar as the selected category
        categoryName.setTitle(s);

        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {


                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked())
                    menuItem.setChecked(false);
                else
                    menuItem.setChecked(true);

                //Closing drawer on item click
                drawerLayout.closeDrawers();

                //Check to see which item was being clicked and open the Appopriate news accordingly
                switch (menuItem.getItemId()) {

                    case R.id.itemWorld:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=world";
                        setTitle("World News");

                        basicDefaults();
                        return true;
                    case R.id.itemFootball:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=football";
                        setTitle("Football News");
                        basicDefaults();
                        return true;
                    case R.id.itemFashion:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=fashion";
                        setTitle("Fashion News");
                        basicDefaults();
                        return true;
                    case R.id.itemSports:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=sport";
                        setTitle("Sports News");
                        basicDefaults();
                        return true;
                    case R.id.itemBusiness:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=business";
                        setTitle("Business News");
                        basicDefaults();
                        return true;
                    case R.id.itemTechnology:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=technology";
                        setTitle("Technology News");
                        basicDefaults();
                        return true;
                    case R.id.itemOpinion:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=commentisfree";
                        setTitle("Opinions");
                        basicDefaults();
                        return true;
                    case R.id.itemCulture:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=culture";
                        setTitle("Culture News");
                        basicDefaults();
                        return true;
                    case R.id.itemTravel:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=travel";
                        setTitle("Travel News");
                        basicDefaults();
                        return true;
                    case R.id.itemLifestyle:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=lifeandstyle";
                        setTitle("LifeStyle News");
                        basicDefaults();
                        return true;
                    case R.id.itemEnvironment:
                        GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=environment";
                        setTitle("Environment News");
                        basicDefaults();
                        return true;

                    default:
                        Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                        return true;

                }
            }
        });

        // Initializing Drawer Layout and ActionBarToggle
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

                super.onDrawerOpened(drawerView);

            }
        };

        //calling sync state is necessay or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }

PS.- 我已经尝试了其他方法,比如在styles.xml文件中的apptheme中添加此内容。

<item name="android:activatedBackgroundIndicator">@drawable/drawer_selected_item</item>

但是我仍然找不到解决方案。
请帮忙,这是我项目中剩下的最后一件事。


请参考以下链接 link1, link2link3,这将对您有所帮助。 - vijay chhalotre
@vijaychhalotre 我看过这些,但我仍然无法更改所选项目的背景颜色。 - Manmeet Singh
3个回答

29

我已经找到了解决方案-

在NavigationView中,我做了以下操作-

        app:itemBackground="@drawable/drawer_selected_item"

因此,我的NavigationView看起来像这样 -

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@color/colorPrimary"
            app:headerLayout="@layout/header"
            app:itemIconTint="@drawable/drawer_item"
            app:itemTextAppearance="@style/TextAppearance20"
            app:itemTextColor="@drawable/drawer_item"
            app:menu="@menu/drawer"
            app:itemBackground="@drawable/drawer_selected_item"
tools:context="com.androidexample.newssnips.app.NavigationDrawerFragment" />

我修改了drawer_selected_item所在的文件,具体如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@color/colorAccent"/>
<item android:drawable="@android:color/transparent" />
</selector>

1
这是唯一对我有效的解决方案,使用androidx.drawerlayout.widget.DrawerLayout和com.google.android.material.navigation.NavigationView :) 谢谢。 - TinaFrieda
如果我也想改变文本颜色,该怎么办? - Noman Aziz

0

NavigationView有一个叫做setItemTextColor()的方法。它使用ColorStateList作为参数。navigationView.setItemTextColor(),参数为ColorStateList。


仍然无法正常工作。但是如果您可以详细说明您的答案,我可能会漏掉了某些东西。 - Manmeet Singh

0

Caspian的回答进行解释:

Android开发者文档提供了ColorStateList,因此您可以在Android中尝试不同状态的视图。

示例代码在这里:ColorStateList Android Example


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接