更改导航视图单个特定菜单项的背景颜色 [英] Change background color of single specific menu items of navigationView

查看:20
本文介绍了更改导航视图单个特定菜单项的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在导航抽屉内的 android 菜单中设置所有标题项的背景颜色.我的布局看起来像:

<item android:title="TopItem" android:id="@+id/top_item1">//这里我要设置背景<菜单><组><item android:id="@+id/sub_item1"android:title="SubItem"/>//这里没有背景</组></菜单></项目><item android:title="TopItem" android:id="@+id/top_item2"><菜单><组><item android:id="@+id/sub_item2"android:title="SubItem"/><item android:id="@+id/sub_item3"android:title="SubItem"/><item android:id="@+id/sub_item4"android:title="SubItem"/></组></菜单></菜单>

结果应该类似于:

我发现我可以使用以下方法设置文本颜色:

MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_item);SpannableString s = new SpannableString(menuItem.getTitle());s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance), 0, s.length(), 0);如果 (menuItem.getItemId()==R.id.nav_targets){menuItem.setTitle(s);}

但是如何设置填充背景颜色?

解决方案

更改单个特定菜单项的背景颜色

AFAIK 使用菜单这是不可能的,您需要创建自定义 navigationView

当您使用 BackgroundColorSpan 为菜单项设置背景时,它只会将背景设置为菜单项标题而不是整个视图

<块引用>

输出使用 BackgroundColorSpan

<块引用>

尝试使用 RecyclerView

activity_main.xml

<包括布局="@layout/app_bar_main"android:layout_width="match_parent"android:layout_height="match_parent"/><android.support.design.widget.NavigationViewandroid:id="@+id/nav_view"android:layout_width="wrap_content"android:layout_height="match_parent"android:layout_gravity="开始"android:fitsSystemWindows="true"><线性布局android:layout_width="match_parent"android:layout_height="match_parent"机器人:方向=垂直"><include layout="@layout/nav_header_main"/><android.support.v7.widget.RecyclerViewandroid:id="@+id/navRecyclerView"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout></android.support.design.widget.NavigationView></android.support.v4.widget.DrawerLayout>

<块引用>

主活动

公共类 MainActivity 扩展 AppCompatActivity实现 NavigationView.OnNavigationItemSelectedListener {RecyclerView navRecyclerView;LinearLayoutManager layoutManager;ArrayListarrayList = 新的 ArrayList<>();NavigationAdapter 适配器;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);工具栏工具栏 = (工具栏) findViewById(R.id.toolbar);setSupportActionBar(工具栏);DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);ActionBarDrawerToggle 切换 = 新的 ActionBarDrawerToggle(这个,抽屉,工具栏,R.string.navigation_drawer_open,R.string.navigation_drawer_close);drawer.addDrawerListener(toggle);切换.syncState();NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);navigationView.setNavigationItemSelectedListener(this);navRecyclerView = findViewById(R.id.navRecyclerView);navRecyclerView.setHasFixedSize(true);layoutManager = new LinearLayoutManager(this);navRecyclerView.setLayoutManager(layoutManager);initArray();适配器 = 新的 NavigationAdapter(this, arrayList);navRecyclerView.setAdapter(适配器);}私有无效initArray(){NavigationDataModel 模型 = 新的 NavigationDataModel();model.setColor(ContextCompat.getColor(this, R.color.colorPrimary));模型.setIcon(R.drawable.ic_menu_gallery);模型.setTitle("项目1");arrayList.add(model);NavigationDataModel model2 = new NavigationDataModel();model2.setColor(ContextCompat.getColor(this, R.color.colorRed));model2.setIcon(R.drawable.ic_menu_camera);model2.setTitle("项目2");arrayList.add(model2);NavigationDataModel model3 = new NavigationDataModel();model3.setColor(ContextCompat.getColor(this, R.color.colorGreen));model3.setIcon(R.drawable.ic_menu_send);model3.setTitle("项目3");arrayList.add(model3);NavigationDataModel model4 = new NavigationDataModel();model4.setColor(ContextCompat.getColor(this, R.color.colorPink));model4.setIcon(R.drawable.ic_menu_share);model4.setTitle("项目4");arrayList.add(model4);}@覆盖公共无效 onBackPressed() {DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);如果 (drawer.isDrawerOpen(GravityCompat.START)) {drawer.closeDrawer(GravityCompat.START);} 别的 {super.onBackPressed();}}@覆盖公共布尔 onCreateOptionsMenu(菜单菜单){//给菜单充气;如果它存在,这会将项目添加到操作栏.getMenuInflater().inflate(R.menu.main, menu);返回真;}@覆盖公共布尔 onOptionsItemSelected(MenuItem item) {//在此处处理操作栏项目的点击.操作栏将//自动处理 Home/Up 按钮上的点击,这么长时间//当您在 AndroidManifest.xml 中指定父活动时.int id = item.getItemId();//不检查SimplifiableIfStatement如果(id == R.id.action_settings){返回真;}返回 super.onOptionsItemSelected(item);}@SuppressWarnings("StatementWithEmptyBody")@覆盖public boolean onNavigationItemSelected(MenuItem item) {//在此处处理导航视图项的点击.int id = item.getItemId();DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);drawer.closeDrawer(GravityCompat.START);返回真;}}

<块引用>

导航适配器

public class NavigationAdapter extends RecyclerView.Adapter{上下文上下文;ArrayListarrayList = 新的 ArrayList<>();公共导航适配器(上下文上下文,ArrayListarrayList){this.context = 上下文;this.arrayList = arrayList;}@非空@覆盖public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {视图视图 = LayoutInflater.from(context).inflate(R.layout.custom_layout, parent, false);返回新的 ViewHolder(view);}@覆盖public void onBindViewHolder(@NonNull ViewHolder holder, int position) {holder.navIcon.setImageResource(arrayList.get(position).getIcon());holder.rootView.setBackgroundColor(arrayList.get(position).getColor());holder.navTitle.setText(arrayList.get(position).getTitle());}@覆盖公共 int getItemCount() {返回 arrayList.size();}公共类 ViewHolder 扩展 RecyclerView.ViewHolder {图像视图导航图标;文本视图导航标题;LinearLayout 根视图;公共 ViewHolder(查看 itemView){超级(项目视图);rootView = itemView.findViewById(R.id.rootView);navIcon = itemView.findViewById(R.id.navIcon);navTitle = itemView.findViewById(R.id.navTitle);}}}

<块引用>

导航数据模型

public class NavigationDataModel {私有整数图标,颜色;私人字符串标题;公共 int getIcon() {返回图标;}public void setIcon(int icon) {this.icon = 图标;}公共 int getColor() {返回颜色;}public void setColor(int color) {this.color = 颜色;}公共字符串 getTitle() {返回标题;}公共无效设置标题(字符串标题){this.title = 标题;}}

输出

I want to set the background color of all header items in a android menu within a navigation drawer. My layout looks like:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:title="TopItem" android:id="@+id/top_item1"> // Here i want to set the background
    <menu>
      <group>
        <item android:id="@+id/sub_item1"
            android:title="SubItem" /> // Here no background
      </group>
    </menu>
  </item>
  <item android:title="TopItem" android:id="@+id/top_item2">
    <menu>
      <group>
       <item android:id="@+id/sub_item2"
            android:title="SubItem" />
        <item android:id="@+id/sub_item3"
            android:title="SubItem" />
       <item android:id="@+id/sub_item4"
            android:title="SubItem" />
      </group>
    </menu>
</menu>

Result should kinda look like:

I found out that i can set the text color by using something like:

MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_item);
SpannableString s = new SpannableString(menuItem.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance), 0, s.length(), 0);

if (menuItem.getItemId()==R.id.nav_targets){            
  menuItem.setTitle(s); }

But how can i set the filling background color?

解决方案

Change background color of single specific menu items

AFAIK Using menu this is not possible you need to create custom navigationView

When you use BackgroundColorSpan to set background to your menu item it only set the background to menu item title not whole view

OUTPUT USING BackgroundColorSpan

Try this way using RecyclerView

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/nav_header_main" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/navRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

MainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    RecyclerView navRecyclerView;
    LinearLayoutManager layoutManager;
    ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
    NavigationAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(this);

        navRecyclerView = findViewById(R.id.navRecyclerView);
        navRecyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        navRecyclerView.setLayoutManager(layoutManager);

        initArray();

        adapter = new NavigationAdapter(this, arrayList);
        navRecyclerView.setAdapter(adapter);


    }

    private void initArray() {

        NavigationDataModel model = new NavigationDataModel();
        model.setColor(ContextCompat.getColor(this, R.color.colorPrimary));
        model.setIcon(R.drawable.ic_menu_gallery);
        model.setTitle("Item 1");
        arrayList.add(model);


        NavigationDataModel model2 = new NavigationDataModel();
        model2.setColor(ContextCompat.getColor(this, R.color.colorRed));
        model2.setIcon(R.drawable.ic_menu_camera);
        model2.setTitle("Item 2");
        arrayList.add(model2);

        NavigationDataModel model3 = new NavigationDataModel();
        model3.setColor(ContextCompat.getColor(this, R.color.colorGreen));
        model3.setIcon(R.drawable.ic_menu_send);
        model3.setTitle("Item 3");
        arrayList.add(model3);

        NavigationDataModel model4 = new NavigationDataModel();
        model4.setColor(ContextCompat.getColor(this, R.color.colorPink));
        model4.setIcon(R.drawable.ic_menu_share);
        model4.setTitle("Item 4");
        arrayList.add(model4);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

NavigationAdapter

public class NavigationAdapter extends RecyclerView.Adapter<NavigationAdapter.ViewHolder> {

    Context context;
    ArrayList<NavigationDataModel> arrayList = new ArrayList<>();

    public NavigationAdapter(Context context, ArrayList<NavigationDataModel> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.custom_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.navIcon.setImageResource(arrayList.get(position).getIcon());
        holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
        holder.navTitle.setText(arrayList.get(position).getTitle());
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView navIcon;
        TextView navTitle;
        LinearLayout rootView;

        public ViewHolder(View itemView) {
            super(itemView);
            rootView = itemView.findViewById(R.id.rootView);
            navIcon = itemView.findViewById(R.id.navIcon);
            navTitle = itemView.findViewById(R.id.navTitle);
        }
    }
}

NavigationDataModel

public class NavigationDataModel {
    private int icon, color;
    private String title;

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

OUTPUT

这篇关于更改导航视图单个特定菜单项的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆