I'm trying to dynamically change the color of a custom view but I can't figure out what needs to be accessed and set to achieve this. Here is my code:
Context context;
RectView rv;
LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug);
context = this;
ll = (LinearLayout) findViewById(R.id.debugLayout);
rv = new RectView(context, 0, 100, 0, 100, true, false, "06:45 PM");
ll.addView(rv);
ll.postInvalidate();
}
public void changeColor(View view){
//Color change code goes here
}
private class RectView extends View{
float leftX, rightX, topY, bottomY;
boolean isAppt;
boolean isBeforeTime;
public Paint rectPaint;
private RectF rectangle;
String time;
public RectView(Context context, float _leftX, float _rightX, float _topY, float _bottomY,
boolean _isAppt, boolean _isBeforeTime, String _time){
super(context);
leftX = _leftX;
rightX = _rightX;
topY = _topY;
bottomY = _bottomY;
isAppt = _isAppt;
isBeforeTime = _isBeforeTime;
time = _time;
init();
}
private void init(){
rectPaint = new Paint();
if(leftX > rightX || topY > bottomY)
Toast.makeText(context, "Incorrect", Toast.LENGTH_SHORT).show();
MyUtility.LogD_Common("Left = " + leftX + ", Top = " + topY + ", Right = " + rightX +
", Bottom = " + bottomY);
rectangle = new RectF(leftX, topY, rightX, bottomY);
float height = bottomY;
float width = rightX - leftX;
MyUtility.LogD_Common("Height = " + height + ", Width = " + width);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT, (int) height);
params.leftMargin = (int) leftX;
//params.rightMargin = 10;
setLayoutParams(params);
}
public void setBeforeTime(boolean _isBeforeTime){
isBeforeTime = _isBeforeTime;
}
protected void onDraw(Canvas canvas){
if(isAppt){
if(isBeforeTime)
rectPaint.setARGB(144, 119, 98, 95);
else
rectPaint.setARGB(144, 217, 131, 121);
//119,98,95
rectPaint.setStyle(Style.FILL);
}
else{
rectPaint.setARGB(0, 0, 0, 0);
rectPaint.setStyle(Style.FILL);
}
canvas.drawRect(rectangle, rectPaint);
if(isAppt){
rectPaint.setColor(Color.RED);
rectPaint.setStrokeWidth(2);
rectPaint.setStyle(Style.STROKE);
canvas.drawRect(rectangle, rectPaint);
}
}
}
and here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/debugLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change color"
android:onClick="changeColor" />
</LinearLayout>
Since I'm not setting the background I can't get the background and change the color that way. The rectangle also needs to have both the stroke and the fill and be created dynamically. How do I go about changing the fill?