0

我试图在按钮单击时调用 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);              
        }
    });
4

3 回答 3

1

你应该用小写字母调用一个实例,因为它不是一个类:lineView insted of LineView。

由于您是从另一个线程(UI)调用它,您应该说

LineView.postInvalidate();

当您第一次创建 LineView 实例时,onDraw 将自行执行并显示第一行。

不清楚什么是 LineView.draw(cv); 您可以在绘制线条之前在 onDraw 中绘制背景图像。您可以在自定义视图中使用 onSizeChange 方法来查找其实际尺寸并调整位图大小...

在 onDraw 中插入一行

Log.e("LineView", Integer.toString(getNewX()));

然后在 DDMS - LogCat 中查看按钮时的输出。

于 2012-01-05T11:24:52.503 回答
0

试试这个:

你没有像你应该的那样创建 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);              
    }
});
于 2012-01-05T11:28:52.760 回答
0

解决了,我在xml布局中放置了自定义视图,它工作正常。

于 2012-01-06T04:29:22.400 回答