0
我試圖動態更改自定義視圖的顏色,但我無法弄清楚需要訪問和設置以實現此目的。這裏是我的代碼:更改自定義視圖的顏色
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>
由於我沒有設置背景我不能讓背景和改變顏色的方式。矩形也需要同時具有筆畫和填充,並且可以動態創建。我如何去改變填充?
在代碼貼上面,我是設置了油漆的顏色,當我第一次創建矩形。我想改變顏色並重新繪製矩形;然而,調用'rv.setBeforeTime(true); ll.postInvalidate();'似乎沒有辦法。 – SecretBit
也許你想刪除矩形並繪製一個新的。 [在Android中添加和刪除視圖動態?](http://stackoverflow.com/questions/3995215/add-and-remove-views-in-android-dynamically/3995335#3995335) – chinglun
另一個奇怪的是代碼工作在模擬器上罰款,但不適用於實際設備。是的,這是我可能想嘗試的。 – SecretBit