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-styleable name="DrawingView">
<!-- drawing view color attributes -->
<attr name="dv_background_color" format="color" />
<attr name="dv_foreground_color" format="color" />
<!-- You can add other custom attributes also -->
<attr name="dv_padding" format="dimension" />
<attr name="dv_width" format="dimension" />
</declare-styleable>
Now write the below code in your java class file :
public class DrawingView extends View {
//Default colors
private int mDrawingViewBackgroundColor = 0xFF0000FF;
private int mDrawingViewForegroundColor = 0xFF0000FF;
//Default padding
private int mViewPadding = 5;
private int mViewWidth = 10;
private Paint mForeGroundColorPaint = new Paint();
private Path mBackGroundColorPaint = new Path();
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typeArr = 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);
}
@Override
public void invalidate() {
setupPaints();
super.invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
Post a Comment for "How To Change A View From A Different Activity."