Android - 从asynctask更新自定义视图

时间:2014-01-31 21:37:16

标签: android android-asynctask

我有自定义视图类

public class DrawingView extends View {

//drawing path
private Path drawPath;
//drawing and canvas paint
private Paint drawPaint, canvasPaint;
//initial color
private int paintColor = 0x00660000;

...
public void printPoint(Point p, Boolean b){
    if(p != null){
        Paint testePaint = new Paint();
        testePaint.setColor(0xFF0000FF);
        testePaint.setAntiAlias(true);
        testePaint.setStrokeWidth(brushSize);
        testePaint.setStyle(Paint.Style.STROKE);
        testePaint.setStrokeJoin(Paint.Join.ROUND);
        testePaint.setStrokeCap(Paint.Cap.ROUND);
        if(b){
            testePaint.setColor(0xFFFF0000);
        }else{
            testePaint.setColor(0xFF0000FF);
        }
        drawCanvas.drawPoint(p.x, p.y, testePaint);
    }
}

public void printPath(){
    if(paths.size() > 0){
        Path testePath = new Path();

        Paint testePaint = new Paint();
        testePaint.setColor(0xFF00FF00);
        testePaint.setAntiAlias(true);
        testePaint.setStrokeWidth(brushSize);
        testePaint.setStyle(Paint.Style.STROKE);
        testePaint.setStrokeJoin(Paint.Join.ROUND);
        testePaint.setStrokeCap(Paint.Cap.ROUND);

        testePath = paths.remove(0);

        drawCanvas.drawPath(testePath, testePaint);
    }
}
}

将视图添加到布局并使用

将其加载到MainActivity中
public class MainActivity extends Activity implements OnClickListener {

    //TCP COM
    private TcpClient mTcpClient;

    //
    private DrawingView drawView;
    private ImageButton currPaint, drawBtn, eraseBtn, newBtn;

    private float smallBrush, mediumBrush, largeBrush;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
        currPaint = (ImageButton)paintLayout.getChildAt(0);
        currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));

        drawView = (DrawingView)findViewById(R.id.drawing);
        drawView.setBrushSize(mediumBrush);

....
}

当我点击一个按钮时,我调用以下功能

public void updateView(Linha l){
    Log.d("TCP","updateView()");
    if(l.getEscreve() == true){
        drawView.printPath();
    }
    drawView.printPoint(l.getPonto(),l.getEscreve());
}

它可以工作但是当我从asynctask从onProgressUpdate调用它时,如果再次点击按钮,我只能在视图上看到绘图。

2 个答案:

答案 0 :(得分:0)

嗯我认为你不应该在另一个线程上更新UI。而是在自定义视图中覆盖onDraw,并从asynctask do postInvalidate覆盖在UI线程上调用onDraw。

答案 1 :(得分:0)

在drawPath和drawPoint之后添加invalidate();解决了问题:)