seon seon - 17 days ago 6
Android Question

How to switch icons of action bar menu in android

I want to switch the icon in the actionbar on clicking to it.I did the following inside onOptionsItemSelected.

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

case R.id.star_School:
if (isStarFilled) {
item.setIcon(R.mipmap.starfilled);
isStarFilled=true;
}else{
item.setIcon(R.mipmap.star);
isStarFilled=false;
}
return true;
}
return super.onOptionsItemSelected(item);
}


This is not working in my case.This is my menu xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/star_School"
android:icon="@mipmap/star"
android:title="Bookmark"
app:showAsAction="always" />
</menu>


This is my onCreate Method

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_school_details);
Boolean isStarFilled=false;

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getExtras().getString("name"));

viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);

tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

}


cannot resolve symbol isStarFilled?
Can somebody please help me?

Answer

Keep your icons in drawable and compare some thing like this

 mRememberPwd.getDrawable().getConstantState().equals
  (getResources().getDrawable(R.drawable.login_checked).getConstantState())

you can find more answers here on how to compare drawable

you can also try using flag

global variable

boolean  isStarFilled=false;


case R.id.star_School:
            if (isStarFilled) {
                item.setIcon(R.mipmap.starfilled);
             isStarFilled=false;
            }else{
            item.setIcon(R.mipmap.star);
               isStarFilled=true;
               }
            return true;
Comments