how to update a customview according to the data change?

503 Views Asked by At

Currently in my android app, I made a custom view with 8 rect blocks in two different colors. What I want to do is to make the 8 rectangle update the colour according to a array change. Now my code blew could make a static view, how can make it dynamic change, which another class could manipulate this view class object.

public class SampleCanvasActivity extends View {
    Paint paint = new Paint();
    int array[] = new int[8];

    public SampleCanvasActivity(Context context,AttributeSet attributeSet) {
        super(context,attributeSet);
    }

    @Override
    public void onDraw(Canvas canvas) {
        /*
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(130, 130, 180, 180, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(133, 160, 177, 177, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(133, 133, 177, 160, paint );
        */

        for(int i=0;i<array.length;i++){
            array[i] = 0;
        }
        array[7] = 1;

        int left = 50; // initial start position of rectangles (50 pixels from left)
        int top = 50; // 50 pixels from the top
        int width = 50;
        int height = 50;
        for (int row = 0; row < 2; row++) { // draw 2 rows
            left = 50;
            for(int col = 0; col < 4; col++) { // draw 4 columns
                int id = row*4 + col;
                if(array[id]==0)
                paint.setColor(Color.parseColor("#CD5C5C"));
                else
                paint.setColor(Color.CYAN);
                canvas.drawRect(left, top, left+width, top+height, paint);
                left = (left + width + 10); // set new left co-ordinate + 10 pixel gap
                // Do other things here
                // i.e. change colour
            }
            top = top + height + 10; // move to new row by changing the top co-ordinate
        }

    }
}
1

There are 1 best solutions below

0
On

You can use a parameter in custom view, and define a attr in xml.

<resources>
    <declare-styleable name="YourStyle">
        <attr name="YourColor" format="color"></attr>
    </declare-styleable>
</resources>

In SampleCanvasActivity,

get the parameter in your constructor

TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.YourStyle);
Resources mResources = context.getResources();

yourcolor = mTypedArray.getColor(R.styleable.YourStyle_YourColor, mResources.getColor(R.color.YourColor));

And add a setter for yourcolor

public void setYourColor(int innerCircleColor) {
    this. yourcolor = yourcolor;
    invalidate();
}

At last, in onDraw

paint.setColor(yourcolor);

When array is changed, call setYourColor.