0

我正在做一种靶心的类型,但我没有使用圆圈,而是使用正方形。

但问题是:

一切都完成了,生成其他方块颜色的算法也完成了。

但是我实现了一个按钮,我让它刷新了靶心。

问题是我做不到,需要帮助。

这是 MainActivity,我将从这里检测到按钮单击。

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FrameLayout frame = (FrameLayout) findViewById(R.id.frame);

    Draw draw = new Draw(this);
    frame.addView(draw);

    Button refresh = (Button) findViewById(R.id.refresh);

    refresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            draw.onDraw(canvas);
            frame.addView(draw);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
}

这是 Draw 活动,这是我用来渲染图像的活动。

public class Draw extends View {

public Draw(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

Paint prop = new Paint();
Random color = new Random();

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    int width = getWidth();
    int height = getHeight();

    int oriwidth = 0;
    int oriheight = 0;

    for (int x = 0; x < 20; x++) {
        int red = color.nextInt();
        int green = color.nextInt();
        int blue = color.nextInt();
        prop.setARGB(0, red, green, blue);
        canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10,
                height -= 10, prop);
    }
}
}

有人能帮我吗?对不起英语。

4

3 回答 3

2

在 onCreate 期间以编程方式添加 Draw 视图是否有任何特殊原因?尝试在布局 xml 本身中定义 Draw 视图。这应该解决定义视图宽度/高度的任何问题(确保定义宽度和高度......首先尝试硬编码尺寸,如 100dp x 100dp)

完成此操作后,请确保将您的“绘图”视图捕获为活动的成员:

public class MainActivity extends Activity 
{
private Draw mDraw;

然后,在您的 onCreate 中:

mDraw = (Draw)findViewById(R.id.myDrawId);

然后,在您的按钮单击侦听器中,只需调用 invalidate:

refresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mDraw.invalidate();
        }
    });
于 2013-09-24T23:59:51.373 回答
0

尝试使用这部分代码进行更改:

public void onClick(View v) {
     MainActivity.this.draw.onDraw(canvas);
     MainActivity.this.frame.addView(draw);
}
于 2013-09-24T23:03:22.077 回答
0

你不应该onDraw()直接打电话。试试draw.invalidate()

于 2013-09-24T23:08:40.050 回答