【问题标题】:Multiple duplicated Views causes lag when added to layout多个重复的视图添加到布局时会导致延迟
【发布时间】: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


    【解决方案1】:

    如果您创建大量小部件/视图,那么 Android 会变得非常慢,因为它必须尝试计算每个小部件/视图的位置,然后还必须单独绘制每个小部件。

    对于这样的事情,您应该创建一个自定义视图,然后一次性绘制所有星星。

    有关如何执行此操作的更多信息,请参见此处:http://developer.android.com/training/custom-views/custom-drawing.html

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2012-07-26
      • 2011-01-25
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多