Android - 如何在菜单项被点击时更改图标

4

我当前的菜单中只有一项,是一只猪的图标。我希望当我点击这只猪时,图标会变成另一张图片,比如一只鸡。我已经阅读了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;
}
1个回答

6

onOptionsItemSelected会在选中选项菜单中的某个项目时被调用。item参数包含所选菜单项。

因此,你可以这样做:

item.setIcon(R.drawable.chicken);

1
@ojboba 我们都曾经历过这种情况。 - Sarantis Tofas
不适用于我。 - Noor Hossain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接