Search code examples
androidbackgroundandroid-listviewandroid-viewbinder

How can I have my ListView items have (and maintain) different backgrounds?


I have achieved something similar for particular items within my ListView in this question.

However, now, I want the user to be able to click on items, which will essentially highlight any item the user has tapped. I keep a list of the tapped items in my application, and should be able to reference this from the ViewBinder when scrolling occurs, however, since I am never adapting anything to the LinearLayout that makes up the ListView itself, I am not sure how to get the LinearLayout object in order to properly set its background color.

I need to be able to do this, because as you may know, when scrolling, Android re-uses the list items, which is fine unless you are changing formatting (coloring, etc.) of individual list items. In that case, you end up with list items that are colored/formatted incorrectly. I am using a ViewBinder to solve the issue when it comes to the TextViews within my list items, but do not know how to do something similar for the background of the ListView itself.


Solution

  • Create a custom row layout- e.g. custom_row.xml, and arrange any views needed, just as you would in a normal layout for an activity (so in this case you would probably provide a textview for the text, and perhaps an icon to the left of it).

    Then create your custom adapter by extending an existing adapter, and override the getView method as such. Here's an example that uses a layout custom_row with both a title and subtitle:

    class CustomAdapter<T> extends ArrayAdapter<T> {
    
    /** List item title */
    protected TextView mTitle;
    /** List item subtitle */
    protected TextView mSubtitle;
    
    /**
     * @param context
     *            Current context
     * @param items
     *            Items being added to the adapter
     */
    public CustomAdapter(final Context context, final List<T> items) {
        super(context, R.layout.custom_row, items);
    }
    
    /** Construct row */
    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            final LayoutInflater li = (LayoutInflater) getContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.custom_row, null);
        }
        mTitle = (TextView) view.findViewById(R.id.custom_row_title);
        mSubtitle = (TextView) view.findViewById(R.id.custom_row_subtitle);
        return view;
    }
    }
    

    As demonstrated, you can grab the items specified in the custom_row layout you created through the inflater service. Then you can manipulate the objects as needed.