如何在JAVA代码中动态更改操作栏图标?
查看图片,图标编号2。
我想要做的是在我得到的两个图标之间翻转。例如,当用户点击"搜索图标[2]"它将改变世界图标。
所以我得到了代码。
menu.xml
<item android:id="@+id/actionMenu"
android:icon="@drawable/icon1"
android:showAsAction="ifRoom" />
然后我们使用以下命令在JAVA代码中启用菜单:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
然后,我们来处理这个问题 首先,我们进行切换以了解是否存在点击。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionMenu:
changeIcon(); // Here we call that magic function
return true;
default:
return super.onOptionsItemSelected(item);
}
}
那么,我们调用changeIcon();这个功能需要魔法
private void changeIcon(){
try {
if(this.theSwitcher){
// What code need this function?
// I just need to change icon1 to icon2
this.theSwitcher = false;
} else {
// What code need this function?
// I just need to change icon2 to icon1
this.quince = true;
}
} catch (Exception e) {
Log.e("MyBad", "Error: " + e);
}
}
答案 0 :(得分:0)
尝试以下
private void changeIcon(){
MenuItem mi = mMenu.findItem(R.id.actionMenu);
try {
if(this.theSwitcher){
// What code need this function?
// I just need to change icon1 to icon2
mi.setIcon(R.drawable.icon2);
this.theSwitcher = false;
} else {
// What code need this function?
// I just need to change icon2 to icon1
mi.setIcon(R.drawable.icon1);
this.quince = true;
}
} catch (Exception e) {
Log.e("MyBad", "Error: " + e);
}
}
并在
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
mMenu = menu;
}