ListView item background via custom selector

前端 未结 10 1535
深忆病人
深忆病人 2020-11-22 08:19

Is it possible to apply a custom background to each Listview item via the list selector?

The default selector specifies @android:color/transparent for t

10条回答
  •  时光取名叫无心
    2020-11-22 09:16

    FrostWire Team over here.

    All the selector crap api doesn't work as expected. After trying all the solutions presented in this thread to no good, we just solved the problem at the moment of inflating the ListView Item.

    1. Make sure your item keeps it's state, we did it as a member variable of the MenuItem (boolean selected)

    2. When you inflate, ask if the underlying item is selected, if so, just set the drawable resource that you want as the background (be it a 9patch or whatever). Make sure your adapter is aware of this and that it calls notifyDataChanged() when something has been selected.

          @Override
      public View getView(int position, View convertView, ViewGroup parent) {
          View rowView = convertView;
          if (rowView == null) {
              LayoutInflater inflater = act.getLayoutInflater();
              rowView = inflater.inflate(R.layout.slidemenu_listitem, null);
              MenuItemHolder viewHolder = new MenuItemHolder();
              viewHolder.label = (TextView) rowView.findViewById(R.id.slidemenu_item_label);
              viewHolder.icon = (ImageView) rowView.findViewById(R.id.slidemenu_item_icon);
              rowView.setTag(viewHolder);
          }
      
          MenuItemHolder holder = (MenuItemHolder) rowView.getTag();
          String s = items[position].label;
          holder.label.setText(s);
          holder.icon.setImageDrawable(items[position].icon);
      
          //Here comes the magic
          rowView.setSelected(items[position].selected);
      
          rowView.setBackgroundResource((rowView.isSelected()) ? R.drawable.slidemenu_item_background_selected : R.drawable.slidemenu_item_background);
      
          return rowView;
      }
      

    It'd be really nice if the selectors would actually work, in theory it's a nice and elegant solution, but it seems like it's broken. KISS.

提交回复
热议问题