必须有一种更好的方法来执行此操作,但是我尝试过的所有操作都失败了。我不确定,也许我必须以编程方式创建textViews。

我有这个:

if (totalCount[0] > 0) {
    b1Pct = df.format((totalMs[0] / (float) totalTestMs) * 100);
    b1 = df.format((totalBits[0] / totalCount[0]) / 1000000);
}
if (totalCount[1] > 0) {
    b2Pct = df.format((totalMs[1] / (float) totalTestMs) * 100);
    b2 = df.format((totalBits[1] / totalCount[1]) / 1000000);
}
if (totalCount[2] > 0) {
    b3Pct = df.format((totalMs[2] / (float) totalTestMs) * 100);
    b3 = df.format((totalBits[2] / totalCount[2]) / 1000000);
}


如您所见,我需要一个循环来缩减此代码,实际上它需要另外6个条目。我想做这样的事情,但它不符合我的期望:

for (var i=0; i < totalCount.length; i++) {

var count = i+1;

    if (totalCount[i] > 0) {
        "b"+count+"Pct" = df.format((totalMs[i] / (float) totalTestMs) * 100);
        "b"+count = df.format((totalBits[i] / totalCount[i]) / 1000000);
        "Bucket"+count.setText(b+count); "Bucket"+count+"pct".setText("b"+count+"Pct");
    }
}


显然,这是行不通的。

编辑

我削减了整整一行,所以谢谢。我确定它仍然可以改进?

DecimalFormat df = new DecimalFormat("0.00");

String[] percentages = { "b1Pct", "b2Pct", "b3Pct", "b4Pct", "b5Pct", "b6Pct", "b7Pct", "b8Pct", "b9Pct", "b10Pct" };
String[] mbpsResults = { "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10" };
TextView[] buckets = { Bucket1, Bucket2, Bucket3, Bucket4, Bucket5, Bucket6, Bucket7, Bucket8, Bucket9, Bucket10 };
TextView[] bucketsPct = { Bucket1pct, Bucket2pct, Bucket3pct, Bucket4pct, Bucket5pct, Bucket6pct, Bucket7pct, Bucket8pct, Bucket9pct, Bucket10pct };

for (int j = 0; j < totalCount.length; j++) {

if (totalCount[j] > 0) {
    percentages[j] = df.format((totalMs[j] / (float) totalTestMs) * 100);
    mbpsResults[j] = df.format((totalBits[j] / totalCount[j]) / 1000000);
    buckets[j].setText(mbpsResults[j]);
    bucketsPct[j].setText(percentages[j]);
}

else {
    buckets[j].setText("0");
    bucketsPct[j].setText("0");
}
}

最佳答案

是的,以编程方式创建视图是一种解决方案(当然,这样做之后,将它们放入数组或ArrayList中)。但是,您可以随后将这些项添加到数组中。


EditText [] textBoxes =新的EditText [numberOfViews];

textBoxes [0] = findViewById(R ....);

textBoxes [1] = findVi ...


手动创建它们的方法是仅创建一个新的EditText对象,并设置所有在xml文件中设置的参数。例如,你会

for(int i = 0; i < amount; i++) {
    textBoxes[0] = new EditText(this);
    textBoxes[0].setWidth(...);
}


当然,之后您必须将它们添加到父视图(活动)中。

希望这可以帮助!

08-03 20:36