【问题标题】:Use a for loop to speed up defining variables Java Android使用 for 循环加速定义变量 Java Android
【发布时间】:2013-03-20 08:48:17
【问题描述】:

我知道您不能使用 for 循环来创建具有数字模式名称的多个变量,但是有什么方法可以使用某种循环来简化以下代码行?否则它是一个非常长的文件,它做的很少,我不喜欢这样!这是我的代码的缩短版本。

public DrawGrid(Context context, int[] binary) {...
sq00c = binary[0];  
sq01c = binary[1];  
sq02c = binary[2]; ...etc}

Rect sq00 = new Rect(); Paint sq00p = new Paint();  int sq00c;  
Rect sq01 = new Rect(); Paint sq01p = new Paint();  int sq01c;  
Rect sq02 = new Rect(); Paint sq02p = new Paint();  int sq02c; ...ect

protected void onDraw(Canvas canvas) {...
sq00.set(2*sqsize, line0, 3*sqsize, line0+sqsize);  sq00p.setColor(sq00c);  sq00p.setStyle(Paint.Style.FILL);   canvas.drawRect(sq00, sq00p);       
sq01.set(3*sqsize, line0, 4*sqsize, line0+sqsize);  sq01p.setColor(sq01c);  sq01p.setStyle(Paint.Style.FILL);   canvas.drawRect(sq01, sq01p);
sq02.set(4*sqsize, line0, 5*sqsize, line0+sqsize);  sq02p.setColor(sq02c);  sq02p.setStyle(Paint.Style.FILL);   canvas.drawRect(sq02, sq02p);
...etc}

上述三部分代码中的每一部分各出现 64 次。有没有办法用循环来简化它?谢谢

【问题讨论】:

  • 不能用数组吗?
  • 我在这里的一个类似问题中读到过,但不知道如何在我的情况下实现它。
  • 我认为数组或列表可以帮助你,如果可以的话我可以举个例子
  • 举个例子真的很有帮助。
  • 您可能正在寻找二维数组?

标签: java android loops


【解决方案1】:

保留一个 Rects、Paints 和 int 数组(或者,更好的是,将它们全部放在一个漂亮的封装对象中并保留一个数组)并在循环中初始化它们。

【讨论】:

    【解决方案2】:

    例如,试试这个:

    Rect[] rects=new Rect[SIZE];
    

    看看这个link

    【讨论】:

      【解决方案3】:

      试试这个方法:

      private int[] myInt;
      private Rect[] myRect;
      private Paint[] myPaint;
      
      public DrawGrid(Context context, int[] binary) {
          myInt = binary;
          myRect = new Rect[myInt.length];
          myPaint = new Paint[myInt.length];
      
          for (int i = 0; i < myInt.length; i++) {
              //Put Rect parameters here, you have to take advantage of the "i" variable 
              myRect[i] = new Rect();
      
              myPaint[i] = new Paint();
              myPaint[i].setColor(myInt[i]);
              myPaint[i].setStyle(Paint.Style.FILL);
          }
      }
      
      protected void onDraw(Canvas canvas) {
          for (int i = 0; i < myRect.length; i++) { // < not >
              canvas.drawRect(myRect[i], myPaint[i]);
          }
      }
      

      【讨论】:

      • 这很好用,虽然你有 > 而不是
      猜你喜欢
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2016-11-20
      • 2021-09-03
      • 1970-01-01
      • 2011-12-05
      相关资源
      最近更新 更多