我试图在单击按钮时调用onDraw方法,按钮视图只更新一次,同时调用onDraw方法。但线的位置没有变化。
我有这个自定义视图
public LineSeekbar(Context context) {
super(context);
this.setWillNotDraw(false);
setNewX(130);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.e("GRAPH","draw");
paint = new Paint();
paint.setARGB(225, 215, 10, 20);
paint.setStrokeWidth(2);
paint.setStyle(Style.FILL);
canvas.drawLine(130,900,getNewX(),100, paint);
setNewX(getNewX()+15);
}
从活动类调用此
final Bitmap mBackgroundImage = Bitmap.createBitmap(500,500, Bitmap.Config.RGB_565);
cv =new Canvas(mBackgroundImage);
LineView = new LineSeekbar(LineActivity.this);
LineView.setLayoutParams(new LayoutParams(500,500));
LineView.onMeasure(500,500);
LineView.invalidate();
LineView.draw(cv);
// LineView = null;
ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mImageView.setBackgroundColor(android.R.color.white);
mImageView.setImageBitmap( mBackgroundImage );
LinearLayout ll =(LinearLayout) findViewById(R.id.linearLayout1);
ll.addView(mImageView);
Button inc = (Button) findViewById(R.id.increase);
inc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LineView.invalidate();
LineView.draw(cv);
}
});
您应该用小写字母调用实例,因为它不是类:lineView而不是lineView。
既然你是从另一个线程(UI)调用它,你应该说
LineView.postInvalidate();
当您第一次创建LineView实例时,onDraw将单独执行并显示第一行。
目前尚不清楚什么是LineView.draw(cv);您可以在绘制线条之前在onDraw中绘制背景图像。您可以在自定义视图中使用onSizeChange方法来查找其实际尺寸并调整位图大小。。。
在onDraw中插入一行
Log.e("LineView",Integer.toString(getNewX()));
然后在DDMS-LogCat中按下按钮时查看输出。
试试这个:
您没有像应该的那样创建LineView类的对象。你应该用小写字母举例。
final Bitmap mBackgroundImage = Bitmap.createBitmap(500,500, Bitmap.Config.RGB_565);
cv =new Canvas(mBackgroundImage);
LineView lineView = new LineSeekbar(LineActivity.this);
lineView.setLayoutParams(new LayoutParams(500,500));
lineView.onMeasure(500,500);
lineView.invalidate();
lineView.draw(cv);
// LineView = null;
ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mImageView.setBackgroundColor(android.R.color.white);
mImageView.setImageBitmap( mBackgroundImage );
LinearLayout ll =(LinearLayout) findViewById(R.id.linearLayout1);
ll.addView(mImageView);
Button inc = (Button) findViewById(R.id.increase);
inc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
lineView.invalidate();
lineView.draw(cv);
}
});
解决了这个问题,我在xml布局中放置了自定义视图,它运行良好。