gwtstylescelllist

How can I stop my GWT CellList items from loosing their CSS styles?


I am setting styles on CellList items on an individual basis using:

cellList.getRowElement(0).addClassName("style-name-A");
cellList.getRowElement(1).addClassName("style-name-B");

This is reflected when I run the application. But when I click any row item all the items lose these styles and revert to the standard style of the CellList (as defined in my CellListResources css file). How can I stop this behaviour?

I am adding items to the CellList via a ListDataProvider; using a subclass of MultiSelectionModel to handle selections and have passed in my own CellListResources to the CellList constructor to define the base styles.


Solution

  • This happens because the selection re-renders the row, therefore loosing any changes you would have made to this element.

    The workaround I found for this is to handle it at individual cell level.

    In practice I wrap each of my cells into a "StyleAwareCellDecorator" which creates a span around with a given style. I then decides what style to apply based on some logic. It could be based on the context.getIndex() in your case.

    public class StyleAwareCellDecorator<C> extends AbtractCell<C> {
    
        private final Cell<C> decorated;
        private final MyLogic logic;
    
        public StyleAwareCellDecorator( Cell<C> decorated, MyLogic logic ) {
            this.decorated = decorated;
            this.logic = logic;
        }
    
        void render(Context context, C value, SafeHtmlBuilder sb) {
            String theCssClass = myLogic.decideWhatStyleToUse( context.getIndex() );
            sb.append( ... some tag with class="theCssClass" ... );
            delegated.render( context, value, sb );
            sb.append( ... close tag ... );
        }
    }
    

    With this facility in place you could replace your code with:

    MyLogic myCellStyleLogic;
    myCellStyleLogic.useStyleForRowIndex( "style-name-A", 0 );
    myCellStyleLogic.useStyleForRowIndex( "style-name-B", 1 );
    

    And let say store that in a Map