[英]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. 我要在单击时切换操作栏中的图标。我在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文件
<?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 这是我的onCreate方法
@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? 无法解析符号isStarFilled? Can somebody please help me?
有人能帮帮我吗?
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.