如何在JAVA代码中动态更改操作栏图标?
参见图片,图标编号为2。
(来源:android.com)
我想做的是在两个图标之间切换。例如,当用户单击“搜索图标[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);
}
}
尝试以下
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句