Setting different divider color to each element in list view

前端 未结 2 1129
半阙折子戏
半阙折子戏 2021-01-05 01:15

I want to have a list with different dividers between the list elements. I have used this code to define a white divider with height 1:

_listView.setDivider(         


        
2条回答
  •  萌比男神i
    2021-01-05 02:03

    Set the divider to height to 0 and implement a View in your item layout with the height of 1 and change its color based on the list item every time the view is built.

    Here's an XML layout sample:

    
    
    
        
    
        
    
    
    

    And this is how you change the color in the adapter:

    public class MyAdapter extends BaseAdapter {
        /** List of items to show */
        private ArrayList items = new ArrayList();
        private Context context;
        private int color[];
    
        public OffersAdapter(Context c, ArrayList items, int color[])
        {
            super();
            this.context = c;
            this.items = items;
            this.color = color;
        }
    
        public int getCount() {
            return items.size();
        }
    
        public Object getItem(int position) {
            return null;
        }
    
        public long getItemId(int position) {
            return 0;
        }
    
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
    
        if(null == convertView)
        {
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.list_item, parent, false);
    
            viewHolder.text = (TextView) convertView.findViewById(R.id.text);
            viewHolder.divider = (View) convertView.findViewById(R.id.divider);
    
            convertView.setTag(viewHolder);
        } else {
            //Retrieve the current view
            viewHolder = (ViewHolder) convertView.getTag(); 
        }
    
        //This is where you chance the divider color based on the item  
        viewHolder.divider.setBackgroundColor(color[position]);
    
      viewHolder.text.setText(items.get(position));
    
        return convertView;
    }
    
    //Holds the current view
     private static class ViewHolder {
             public TextView text;
             public View divider;
         }   
    }
    

    Where int color[] is a list of the colors you want to use.

    More about ViewHolder read here.

提交回复
热议问题