我正在尝试动态更改自定义视图的颜色,但我无法弄清楚需要访问和设置的内容以实现此目的。这是我的代码:
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);
}
}
}
,这是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>
由于我没有设置背景,因此无法获得背景并改变颜色。矩形还需要同时具有笔触和填充,并且可以动态创建。我该如何改变填充?
答案 0 :(得分:0)
你的意思是视图的背景颜色?如果是这样,请尝试
view.setBackgroundColor(0xFF00FF00);
OR
view.setBackgroundColor(Color.Red);
这些帖子可能有所帮助: