Skip to content Skip to sidebar Skip to footer

How To Change A View From A Different Activity.

Right now my goal is to have the Colors activity allow users to hit a button to change the color they are drawing with. How do I get the instance of the canvas in my activity_main.

Solution 1:

My understanding is that, you want to change the color of DrawingView view on any event (ex: button click).

For that please follow the below code :

Firstly, create the attribute styles in attrs.xml

<declare-styleablename="DrawingView"><!-- drawing view color attributes --><attrname="dv_background_color"format="color" /><attrname="dv_foreground_color"format="color" /><!-- You can add other custom attributes also --><attrname="dv_padding"format="dimension" /><attrname="dv_width"format="dimension" /></declare-styleable>

Now write the below code in your java class file :

publicclassDrawingViewextendsView {

 //Default colorsprivateintmDrawingViewBackgroundColor=0xFF0000FF;
 privateintmDrawingViewForegroundColor=0xFF0000FF;

 //Default paddingprivateintmViewPadding=5;
 privateintmViewWidth=10;

privatePaintmForeGroundColorPaint=newPaint();
privatePathmBackGroundColorPaint=newPath();

publicDrawingView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArraytypeArr= context.obtainStyledAttributes(attrs, R.styleable.DrawingView);
  try {

    //Inflate all the attributes of DrawingView from xml that are initialize in activity_main.xml layout file.
    mDrawingViewBackgroundColor = typeArr.getColor(R.styleable.DrawingView_dv_background_color, mDrawingViewBackgroundColor);
    mDrawingViewForegroundColor = (R.styleable.DrawingView_dv_background_color, mDrawingViewForegroundColor);

    mViewPadding = (int)typeArr.getDimension(R.styleable.DrawingView_dv_padding, mViewPadding);

    mViewWidth = (int)typeArr.getDimension(R.styleable.DrawingView_dv_width, mViewWidth);
   }finally {
        typeArr.recycle();
    }

    setupPaints();
}

setupPaints() {
   //Render DrawingView colors - Foreground color
   mForeGroundColorPaint.setColor(mDrawingViewForegroundColor);
   mForeGroundColorPaint.setAntiAlias(true);
   mForeGroundColorPaint.setStrokeWidth(5f);
   mForeGroundColorPaint.setStyle(Paint.Style.STROKE);
   mForeGroundColorPaint.setStrokeJoin(Paint.Join.ROUND);

   //Render DrawingView colors - Background color
   mBackGroundColorPaint.setColor(mDrawingViewBackgroundColor);
   mBackGroundColorPaint.setAntiAlias(true);
   mBackGroundColorPaint.setStrokeWidth(5f);
   mBackGroundColorPaint.setStyle(Paint.Style.STROKE);
   mBackGroundColorPaint.setStrokeJoin(Paint.Join.ROUND);
}

@Overridepublicvoidinvalidate() {
    setupPaints();
    super.invalidate();
}

@OverrideprotectedvoidonDraw(Canvas canvas) {
    canvas.drawPath(path, paint);
}

}

Post a Comment for "How To Change A View From A Different Activity."