动态更改android:icon

问题描述 投票:0回答:1

如何在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);
        }

    }
java android android-actionbar
1个回答
0
投票

尝试以下操作

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;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.