2016-09-30 45 views
0

我想要點擊項目菜單上的該項目將更改圖標。在片段中檢查圖像項目菜單

選擇的項目:

button_add_to_wishlist.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item 
    android:state_checked="false" 
    android:drawable="@drawable/ic_add_fav" /> 
<item 
    android:state_checked="true" 
    android:drawable="@drawable/ic_add_fav_fill" /> 

菜單

<item 
    android:id="@+id/add_to_wishlist" 
    android:title="@string/book_btn_text_add_to_wishlist" 
    android:icon="@drawable/button_add_to_wishlist" 
    android:checkable="true" 
    app:showAsAction="always"/> 

回答

0
menu.getMenuItem(position).setIcon(drwable); 
0
<item android:icon="@drawable/Selector for the item"/> 

快樂編碼!

+0

我以前使用過這個,但它不起作用「button_add_to_wishlist」是選擇器,它是一個meni項目的圖標。 – rkovtiuk

0

如何在自定義適配器中設置自定義偵聽器?像這樣的東西:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View row = convertView; 
    final Rowholder; 

    if(row == null) 
    { 
     LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
     row = inflater.inflate(layoutResourceId, parent, false); 
     holder = new Rowholder(); 
     holder.checkbox= (CheckBox) row.findViewById(R.id.myCheckbox); 
     holder.icon= (ImageView) row.findViewById(R.id.myIcon); 

     row.setTag(holder); 
    } 
    else 
    { 
     holder = (Rowholder)row.getTag(); 
    } 
    holder.checkbox.setText("A Box"); 

    //here is the important part where we set the imageview's source 
    //dependig on the checkbox state 
    //a checkChangeListener would also do the deal 
    holder.checkbox.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if(holder.checkBox.isChecked()) { 
       holder.icon.setImageResource(R.drawable.ic_add_fav_fill); 
      }else{ 
       holder.icon.setImageResource(R.drawable.ic_add_fav); 
    }); 


    return row; 
} 

//holder class for your UI-elements 
static class RowHolder { 
    CheckBox checkbox; 
    ImageView icon; 
} 

我希望這可以幫助你!