好吧,我不能通过使用带有最大限制的变量来接收随机数时设置限制值。
我通过方法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;
}
}
你能帮助我吗?
答案 0 :(得分:1)
您永远不会调用seekBarValue
方法,因此变量value
会将0
保留为默认值,因此您正在调用
color.nextInt(0);
抛出IllegalArgumentException
。 nextInt
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;
}