簡體   English   中英

Android - 如何在單擊時更改菜單項圖標

[英]Android - How to change menu item icon when clicked

我目前在菜單中有一個項目是豬的圖標。 我想要發生的是當我點擊豬時,圖標將變為另一個像雞的圖像。 我在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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM