Android - 使用扩展View的类中的变量为随机方法添加限制

时间:2013-09-27 10:24:58

标签: android seekbar

好吧,我不能通过使用带有最大限制的变量来接收随机数时设置限制值。

我通过方法seekBarValue获得限制。

我在调用color.nextInt(value)时添加值来限制;它崩溃了,我不知道发生了什么。我可以插入一个数字,值变量是一个整数值,所以我看不出问题所在。

之前调用seekBarValue方法
public class Draw extends View 
{
    public Draw(Context context) 
    {
        super(context);
    }

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

    @Override
    protected void onDraw(Canvas canvas) 
    {
        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(value);//crashes here
            int green = color.nextInt(value);
            int blue = color.nextInt(value);

            prop.setARGB(255, red, green, blue);
            canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10, height -= 10, prop);
        }

    public int seekBarValue (int seekValue)
    {
        value=seekValue;
        return value;
    }
}

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您永远不会调用seekBarValue方法,因此变量value会将0保留为默认值,因此您正在调用

color.nextInt(0);

抛出IllegalArgumentExceptionnextInt param必须大于0


修改

要避免异常,请尝试进行以下更改.-

@Override
protected void onDraw(Canvas canvas) 
{
    super.onDraw(canvas);

    if (value > 0) {
        int width = getWidth();
        int height = getHeight();

        int oriwidth = 0;
        int oriheight = 0;      

        for (int x = 0; x < 20; x++) 
        {
            int red = color.nextInt(value);//crashes here
            int green = color.nextInt(value);
            int blue = color.nextInt(value);

            prop.setARGB(255, red, green, blue);
            canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10, height -= 10, prop);
        }
    }
}

或者只是确保value大于0

value = Math.max(value, 1);

此外,在设置新值后,您需要invalidate视图,以便调用onDraw方法。如果您从您的活动中手动拨打onDraw(正如我猜的那样),请不要。

public int setValue(int value)
{
    this.value = value;
    invalidate();
    return value;
}