webdevqa.jp.net

NavigationViewの単一の特定のメニュー項目の背景色を変更する

ナビゲーションドロワー内のAndroidメニューにあるすべてのヘッダーアイテムの背景色を設定したいのですが、レイアウトは次のようになります。

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

結果は次のようになります。

enter image description here

次のようなものを使用してテキストの色を設定できることがわかりました。

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

しかし、どうすれば塗りつぶしの背景色を設定できますか?

14

単一の特定のメニュー項目の背景色を変更する

[〜#〜] afaik [〜#〜]メニューを使用してこれを行うことはできません。カスタムnavigationViewを作成する必要があります。

BackgroundColorSpanを使用してメニュー項目に背景を設定すると、ビュー全体ではなく、メニュー項目のタイトルにのみ背景が設定されます。

OUTPUT USINGBackgroundColorSpan

enter image description here

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

[〜#〜]出力[〜#〜]enter image description here

5
Nilesh Rathod

テキストの背景色はBackgroundColorScanで変更できます。

  NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            MenuItem menuItem = navigationView.getMenu().findItem(R.id.your_menu_item_id);
            Spannable spannable = new SpannableString(menuItem.getTitle());
            spannable.setSpan(new BackgroundColorSpan(0xFF00CCCC), 0, menuItem.getTitle().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            menuItem.setTitle(spannable);
4
navigationView.ItemBackground = new ColorDrawable(Android.Graphics.Color.Green);

これは役立つかもしれません。

1
Rugved Marathe

RecyclerViewの代わりにDrawerLayout内でNavigationViewを使用するだけです。

1