我目前的菜单中有一个项目,它是 pig 的图标。我想要发生的是当我点击 pig 时,图标会变成另一个像鸡一样的图像。我已经阅读了 StackOverFlow 上的其他论坛,但仍然没有运气。
我知道您不能使用 findViewbyId 来引用菜单项,但 findItem 方法对我不起作用,或者至少它说无效。请指教。
这是我当前的代码:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/menuImage"
android:title=""
android:icon="@drawable/pig"
android:orderInCategory="1"
app:showAsAction="always|withText"/>
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuImage:
Toast.makeText(this, "YOU THINK YOU GOT THIS?", Toast.LENGTH_SHORT).show();
MenuItem changeImage = (MenuItem) findViewById(R.id.menuImage);
changeImage.setIcon(R.drawable.chicken);
return true;
}
return true;
}
最佳答案
只要选择选项菜单中的项目即可调用onOptionsItemSelected
。item
参数包含选择的菜单项。
所以你可以这样做:
item.setIcon(R.drawable.chicken);
关于Android - 单击时如何更改菜单项图标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44791300/