Search code examples
androidandroid-custom-viewsetter

Update color in customView by setter


I have CustomView and it works ok. Now i need to change some item color by code. So here is the code i have:

CustomView cv = new CustomView(mContext);
cv.setItemColor(Color.parseColor("#e77400"));

inside of my customView i add method:

public void setItemColor(int color){
        mItemColorDefault = color;
        invalidate();
        requestLayout();
    }

but after this nothing happen and customView does not refresh... Please, help to fix this. Thanks!


Solution

    1. There is no need to call requestLayout() unless the size of the CustomView is not changed. This method only relates to views positioning updates.
    2. You must override the onDraw() method as it is the place when your view is drawn. The invalidate() method causes onDraw() to invoked. Use the mItemColorDefault color to draw your view with it in onDraw().

    Here is the example of custom view with onDraw() method overridden:

    https://github.com/dawidgdanski/TicTacToe/blob/master/game/src/main/java/pl/dawidgdanski/tictactoe/game/view/TicTacToeView.java

    Hope this helps somehow.