我目前的菜单中有一个项目,它是猪的图标。我想要发生的是当我点击猪时,图标会变成另一个像鸡一样的图像。我已经阅读了 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;
}
Run Code Online (Sandbox Code Playgroud)
onOptionsItemSelected只要选择选项菜单中的项目时都被调用。该item参数包含选定的菜单项。
所以你可以这样做:
item.setIcon(R.drawable.chicken);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2599 次 |
| 最近记录: |