Change Actionbar button icon

Asked

Viewed 1,247 times

3

I have this layout with this button of heart , it has as inside of the event of click of this button I change the icon

inserir a descrição da imagem aqui

I was hoping to trade my heart for this heart when you click

inserir a descrição da imagem aqui

the answer below solved more generated a problem

You need to overwrite onCreateOptionsMenu and onOptionsItemSelected methods

1) Retain the desired Menuitem:

private MenuItem menuCoracao;
...  
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.seu_menu, menu);
    menuCoracao = menu.findItem(R.id.id_do_seu_menu);
    return super.onCreateOptionsMenu(menu);

} 2) Detect menu click and change icon:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.id_do_seu_menu) {
        menuCoracao.setIcon(R.drawable.seu_drawable);
    }
    return super.onOptionsItemSelected(item);
}

I tried to use on onCreate so

meuCoracao.setIcon(R.drawable.ic_action_favorite_v);

gave this error

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{praias.android.makerapp.com.praias/praias.android.makerapp.com.praias.MainActivity}: java.lang.NullPointerException

1 answer

4


You need to overwrite the methods onCreateOptionsMenu and onOptionsItemSelected

1) Retain the MenuItem desired:

private MenuItem menuCoracao;
...  
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.seu_menu, menu);
    menuCoracao = menu.findItem(R.id.id_do_seu_menu);
    return super.onCreateOptionsMenu(menu);
}

2) Detect menu click and change icon:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.id_do_seu_menu) {
        menuCoracao.setIcon(R.drawable.seu_drawable);
    }
    return super.onOptionsItemSelected(item);
}
  • Is there any way I can start this prayer on onCreate? I tried to use it off onOptionItemSelected and it didn’t work

Browser other questions tagged

You are not signed in. Login or sign up in order to post.