ArrayList元素每次都更改为最后一个条目

时间:2015-07-07 16:19:14

标签: android

我有如下课程。当我运行它时,它应该保存触及屏幕位置的x和y,以便每次触摸时在圆形ArrayList中创建圆圈。但是每次数组列表的所有元素都是最后一个x,y(所有元素都变为最后一个元素)。我该怎么办 ?

package com.siamak.rain.ball;

import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;


public class Balls extends ImageView {

    static ArrayList<Circle> circles = new ArrayList<Circle>();
    static Paint             cp;


    public Balls(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initial();
    }


    public Balls(Context context, AttributeSet attrs) {
        super(context, attrs);
        initial();
    }


    public Balls(Context context) {
        super(context);
        initial();
    }


    public static class Circle {

        static float x;
        static float y;
    }


    public static void initial() {
        cp = new Paint();
        cp.setColor(Color.GREEN);
        cp.setAntiAlias(true);
        cp.setStyle(Style.STROKE);
        cp.setStrokeWidth(5);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction())
        {
            case (MotionEvent.ACTION_DOWN):
                Circle c = new Circle();
                c.x = event.getX();
                c.y = event.getY();
                circles.add(c);
                invalidate();
                break;

        }
        return true;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        for (Circle c: circles)
            canvas.drawCircle(c.x, c.y, 50, cp);
    }
}

0 个答案:

没有答案