Android - 应用程序可能在其主线程上做了很多工作

Android - Application may be doing to much work on its main thread

我知道我的主线程中有很多事情要做,但我正在寻找解决方法。

这是我的应用程序的结构:

目前我有我的主 activity,它有 6 个可点击的图像视图(打开新活动),当打开其中一个活动时会出现问题。在此 activity 中,我使用了带有 3 个选项卡的 SlidingTabLayout。

这就是我想要实现的目标:

我正在用可绘制对象(形状)制作一架钢琴

例如,这是黑键:

<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
<stroke
    android:width="1dp"
    android:color="#FF000000" />

    <solid 
      android:color="#FF000000"/>
</shape> 

然后我在我的布局中调用这个 drawables 来创建钢琴:

<ImageView
    android:layout_width="8dp"
    android:layout_height="37dp"
    android:layout_marginLeft="40dp"
    android:layout_marginStart="10.5dp"
    android:src="@drawable/key_black" />

我正在为每个钢琴显示 7 个黑键图像视图和 10 个白键图像视图,并且每个选项卡有 11 个钢琴。所以这是每个标签 187 个 Imageview。

所以我明白这对我的 CPU 会很苛刻。我正在寻找一种方法来对我的主线程执行此操作?在后台做?做到不卡顿?

所以如上所述,我会为钢琴创建一个基础图像,并根据当前按下的键进行调整。下面的代码显示了总体思路:从 R.drawable 加载基本图像,使用按下的键的索引,以及创建图像的大小 Paths,绘制路径,return 图片。如果您需要澄清,请告诉我。

public Bitmap getPianoImage(Context context, int[] pressedKeyIndices){
    Bitmap pianoImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.pianoBase);
    Canvas canvas = new Canvas(pianoImage);
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);

    for(int pressedKeyIndex : pressedKeyIndices){
        Path path = getPathForKeyIndex(pressedKeyIndex, pianoImage.getWidth(), pianoImage.getHeight());
        canvas.drawPath(path, paint);
    }

    return pianoImage;
}

private Path getPathForKeyIndex(int idx, int w, int h){

    Path path = new Path();

    switch(idx){
        case 0:
            path.moveTo(0f*w, 0f*h); // used for first point
            path.lineTo(0f*w, 1f*h);
            path.lineTo(0.1f*w, 1f*h);
            path.lineTo(0.1f*w, 0.5f*h);
            path.lineTo(0.08f*w, 0.5f*h);
            path.lineTo(0.08f*w, 0f*h);
            path.lineTo(0f*w, 0f*h);
            break;
        case 1: ...
    }

    return path;
}