[英]Change android:icon dynamically
如何在JAVA代碼中動態更改操作欄圖標 ?
參見圖片,圖標編號為2。
(來源: android.com )
我想做的是在兩個圖標之間切換。 例如,當用戶單擊“搜索圖標[2]”時,它將變為世界圖標。
所以有我得到的代碼。
menu.xml
<item android:id="@+id/actionMenu"
android:icon="@drawable/icon1"
android:showAsAction="ifRoom" />
然后我們使用以下代碼初始化菜單:
@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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.