如何通过onclickListener改变的OnDraw属性

如何通过onclickListener改变的OnDraw属性

本文介绍了Android的:如何通过onclickListener改变的OnDraw属性()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的OnDraw()函数。

I have a simple ondraw() function.

private class MyViewCircle extends View {
        public MyViewCircle(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }
        @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            canvas.drawCircle(20, 20, 50,
                    paint);
        }
    }

它的工作原理很好。但我想它更有趣。我创建了一个onclickListener。
evolve.setOnClickListener(新View.OnClickListener(){

It works good. But I want it more interesting. I create a onclickListener.evolve.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //How to change attributes?
        }
    });

当我按一下按钮,属性将被改变。例如,更改为

When I click the button, the attributes will be changed. For example, change to

paint.setColor(Color.BLUE);
canvas.drawCircle(30, 30, 50,paint);

我的问题是:我怎么能实现呢?当我按一下按钮,图像将被自动重新生成。谢谢!

My question is: How could I implement this? When I click the button, the image will be automatically re-generated. Thanks!

推荐答案

您可以使用一个成员变量来存储状态,改变它的onClick ,并检查它在的onDraw

You can use a member variable to store the state, change it onClick, and check it in onDraw.

要适当挂钩的单击事件,确保你在构造函数中调用 setOnClickListener ,并调用无效的onClick 来强制重绘。

To hook up the click event properly, make sure you call setOnClickListener in your constructor, and call invalidate in onClick to force a redraw.

private class MyCircle extends View implements OnClickListener {
  private boolean mDrawBlueCircle = false;
  private Paint mPaint = new Paint();

  public MyCircle(Context context) {
    super(context);
    setOnClickListener(this);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    float x = 20;
    float y = 20;
    float r = 50;
    int color = Color.BLACK;
    if (mDrawBlueCircle) {
      x = 30;
      y = 30;
      color = Color.BLUE;
    }
    mPaint.setColor(color);
    canvas.drawCircle(x, y, r, mPaint);
  }

  @Override
  public void onClick(View v) {
    mDrawBlueCircle = true;
    invalidate();
  }
}

请注意,我还存放了油漆中的一个成员变量 mPaint 。这prevents要在每次抽签周期创建新对象,并减少垃圾收集。

Notice that I also store the Paint in a member variable mPaint. This prevents new objects to be created on each draw cycle and reduces garbage collection.

这篇关于Android的:如何通过onclickListener改变的OnDraw属性()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:44