【发布时间】:2015-03-27 23:59:05
【问题描述】:
我正在创建一个太空游戏,其中我正在创建随机分类的“星星”(白色小圆圈)作为背景的一部分。形状是在 XML 中创建的,其中视图是在 Java 中以编程方式创建的。减去随机大小和位置后,星星基本上都是相同的。如果我将循环更改为仅创建 70 个或更少的视图,则整个应用程序运行良好,在三星 Note 2 上没有减速。理想情况下,我希望在整个应用程序中创建几百颗星而没有延迟。
stars.java
public void setup() {
RelativeLayout fullLayout = (RelativeLayout)activity.findViewById(R.id.fullLayout);
//Creates a new "star" and adds it to my main layout as part of the background
for(int i = 0; i < 750; i++){
Random r = new Random();
int width = r.nextInt(1000);//Using the dynamic screen size but for demonstration I changed the width & height to a hard coded integer.
int height = r.nextInt(500);
int starSize = r.nextInt(5) + 3;
View star = new View(activity);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(starSize, starSize);
star.setBackgroundResource(R.drawable.star);
star.setLayoutParams(params);
star.setX(width);
star.setY(height);
fullLayout.addView(star);
}
}
star.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#FFFFFF" >
</solid>
<!-- view border color and width -->
<stroke
android:width="2dp"
android:color="#88FFFFFF" >
</stroke>
<!-- Here is the corner radius -->
<corners
android:radius="90dp" >
</corners>
</shape>
【问题讨论】:
标签: java android xml performance view