android:随机选择属性的方式
我有一个简单的程序可以通过画布绘制简单的形状。
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.RED);
canvas.drawCircle(89, 150, 30, paint);
}
}
如您所见,圆的属性是
(Color.RED);
(89, 150, 30, paint);
我想创建另一个包含许多其他功能(颜色和坐标)的类并随机选择它们。 那么,数组、数组列表还是其他方式,哪种方式更好呢?有人可以给我一个例子如何做到这一点吗?那么如何随机选取它们并将它们放入绘制函数中呢?干杯!
I have a simple program to draw simple shapes by canvas.
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.RED);
canvas.drawCircle(89, 150, 30, paint);
}
}
As you see, the attributes of the circle is
(Color.RED);
(89, 150, 30, paint);
I want to created another class includes a lot of other features(colors and coordinates) and select them randomly.
So, which way is better, array or arraylist or something else? Could someone gives me an example how to do that? Then how to randomly pick them and put them into the draw function? Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试创建一个简单的 Java 对象来包含所有属性,然后将它们添加到单个列表中并随机选择一个项目:
在您的 View 类中:
Try creating a simple Java object to contain all the attributes, then add them to a single list and choose an item at random:
In your View class:
一般来说,在 Android 上,为了提高性能,我总是倾向于使用 Array 而不是 ArrayList。
要随机选择,您可以使用 Math.random() 方法或 util.Random 对象。使用其中任何一个,您都可以生成索引值并使用该索引从数组中读取数据。
应该非常简单,所以除非您确实需要,否则我不会编写任何代码。
Generally on Android I always aim to use an Array over using an ArrayList for performance.
To pick randomly you can use either the
Math.random()
method or theutil.Random
object. Using either of those you can generate an index value and read the data from the array with that index.Should be pretty simple really so I won't write any code unless you really need that.