0

in my Android App I use an AlertBox for selecting icons. This is done with a custom Adapter. I have a class comming from ImageView which changes the backgrond color for the old selected icon.

All works fine expect that I nees to reset the background color for converted views in the adapter. getBackGroundDrawable always return null? Any idea ???

public View getView(int position, View convertView, ViewGroup parent)
{
    JIconImageView imageView = ((convertView == null) ? new JIconImageView(m_context) : (JIconImageView)convertView);

    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageView.setPadding(2, 2, 2, 2);
    imageView.setIsSelected(m_selected == position);
    imageView.setImageResource(JEntryIconHelper.getIconFromIndex(position));

    return imageView;
}

and from public final class JIconImageView extends ImageViewenter code here

public void setIsSelected(boolean bSelected)
{
    if (m_bSelected = bSelected)
        setBackgroundColor(SELECTED_BACKCOLOR);
    else setBackgroundDrawable(m_background);
}

1 Answers1

0

As far as I know, there's no easy way to get the current theme background color.

One reliable way to do what you want is to save the original background color in a member variable during getView (or you could do this once, earlier, by creating a throwaway JIconImageView). For example, at the point where you bind the adapter:

JIconImageView imageView = new JIconImageView (...);
Drawable origBackground = imageView.getBackground();
imageView = null;

Then, reference imageView.getBackground() in setIsSelected().


Another way would be to use an xml selector; this goes in your "drawables" folder:

<selector 
  xmlns:android="http://schemas.android.com/apk/res/android">

  <item 
    android:state_selected="true"
    android:drawable="@drawable/your_selected_drawable" />

  <item 
    android:drawable="@drawable/your_unselected_drawable" />
</selector>

As you can see, this solution uses drawables rather than colors but, if your icons are fixed size, that is a trivial difference (maybe something similar can be done with colors -- you'll have to research that). The drawback to this method is that you have now hard coded the background colors. At least the definitions are in your resources, though.


You could build on the above by referencing an android style in your icon definition, something like this:

<JIconImageView
  android:id=...
  android:background="@drawable/jicon_background_selector />
Peri Hartman
  • 19,314
  • 18
  • 55
  • 101