Home > Net >  Change color of icon in toolbar when click in android
Change color of icon in toolbar when click in android

Time:05-03

Screen demo

I want to change color of icon favorite in toolbar to red when I click it. How can I do that

CodePudding user response:

This is the way to do this. You can change the icon colour but the function to do it only works on API 26 . To make it work on below API 26, you need to change the icon altogether as there is no other way to change the colour.

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == R.id.delete_icon) {
        isSelected = !isSelected
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Toggle state on devices with API 26 
            if (isSelected) {
                item.iconTintList = ContextCompat.getColorStateList(this, R.color.red)
            } else {
                item.iconTintList = ContextCompat.getColorStateList(this, R.color.white)
            }
        } else {
            // Toggle state on devices with API below 26
            if (isSelected) {
                item.icon =
                    ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24_red)
            } else {
                item.icon = ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24)
            }
        }
        return true
    }
    return super.onOptionsItemSelected(item)
}

CodePudding user response:

*try this code -

 btn.setOnClickListener(view -> {
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));

        });

CodePudding user response:

You could create a global Menu variable and initialize it in the onCreateOptionsMenu() and then use it in your onClick().

private Menu menu;

In your onCreateOptionsMenu()

this.menu = menu;

In your button's onClick() method

menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.red_heart));
  • Related