0

I want to setBackground to a MenuItem on OnprepareMenuOptions Method!

this code where I applying setBackground to MenuItem on OptionsItemSelected

   @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        View usera = findViewById(R.id.usera);
        View userb = findViewById(R.id.userb);
        switch (item.getItemId()){
            case R.id.userb:
        // Here default user styling
                colorb = false;
                if (!colorb){
                    userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));
                    usera.setBackground(null);
                    menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_user_black));
                    menu.getItem(1).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_user_icon));
                }
                Toast.makeText(this, "Default User B Selected", Toast.LENGTH_SHORT).show();
                break;

But I want to apply setBackground to "R.id.userb" while onPrepareMenuOptions or before selection of MenuItem.

I tried this but getting crash

  @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        View userb = findViewById(R.id.userb);
        userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));
        return super.onPrepareOptionsMenu(menu);
    }
userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));

please help me, how should I apply this ^^^^^ userb.setBackground on onPrepareMenuOption?

Hope you got me. Thanks in advance =)

1 Answers1

0

Probably you are getting null pointer exception on userb.setBackground.

Can you try getting userb's view by below method.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    final MenuItem userbMenuItem = menu.findItem(R.id.userb);
    View userb = userbMenuItem.getActionView();
    userb.setBackground(ContextCompat.getDrawable(this, R.drawable.color_btn_effect));
    return super.onPrepareOptionsMenu(menu);
}
Ayush
  • 130
  • 1
  • 8
  • https://stablekernel.com/article/using-custom-views-as-menu-items/ is a good reference. Can look into it for more details. – Ayush Dec 30 '20 at 06:54
  • Yeah you got right, but this reference link switching View and this isn't perfect for this app,... Please give me any alternative solution. – sunakshi sinha Dec 30 '20 at 07:25
  • Yeah, this can be used for case when for menu item, `app:showAsAction="always"` is set. Not so in case if items are shown in overflow menu. For overflow menu, I am not sure how to do it via code, but if it is not menu item specific, like different background for different items, we can set a theme. If that is fine, I will update answer. – Ayush Dec 31 '20 at 06:53
  • May be this will help: https://stackoverflow.com/questions/15338033/using-a-custom-view-for-overflow-menu-items – Ayush Dec 31 '20 at 13:24