When you click the menu in onOptionsItemSelected, you want to change the image and color of the action item in it.

Asked 2 years ago, Updated 2 years ago, 52 views

Change the color of the action item when you click the menu in onOptionsItemSelected.

For example, the following image

Enter a description of the image here

There is a gray (dark) action item on the right side, but when clicked, I would like to do something like make it white, for example.
Also, I would like to do something that turns gray when I click on it when it is white.

I think it's an image replacement, but for example, if you want to change the download color (image) of the code below,
What should I write in onOptionsItemSelected?

Thank you for your cooperation.

onOptionsItemSelectedExample

@Override
public boolean onOptionsItemSelected(MenuItem){
    switch(item.getItemId()){

        case android.R.id.home:
            finish();
            break;
        case R.id.download:
            finish();
            break;
    }
    return super.onOptionsItemSelected(item);
}

android

2022-09-30 20:35

1 Answers

You can change the icon in item.setIcon.
ic_download_on =White Download Icon
ic_download_off=Grey download icon
ic_mail_on=White mail icon
ic_mail_off=Grey mail icon
Think of it as

private boolean mDownloadChecked=false;
private boolean mMailChecked=false;

@ Override
public boolean onOptionsItemSelected(MenuItem){
    switch(item.getItemId()){
        case android.R.id.home:
            finish();
            break;
        case R.id.download:
            mDownloadChecked=!mDownloadChecked;
            item.setIcon(mDownloadChecked? R.drawable.ic_download_on —R.drawable.ic_download_off);
            break;
        case R.id.mail:
            mMailChecked=!mMailChecked;
            item.setIcon(mMailChecked? R.drawable.ic_mail_on —R.drawable.ic_mail_off);
            break;
    }
    return super.onOptionsItemSelected(item);
}


2022-09-30 20:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.