必须有更好的方法来做到这一点,但我尝试过的一切都失败了。也许我必须以编程方式创建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");
}
}
答案 0 :(得分:1)
是的,以编程方式创建视图是一种解决方案(当然,在执行此操作后将它们放入数组或ArrayList中)。但是,您可以在之后将这些项添加到数组中。
EditText [] textBoxes = new 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(...);
}
当然,您必须在之后将它们添加到父视图(活动)中。
希望这有帮助!
答案 1 :(得分:0)
看起来很简单(如果那就是你需要的那样)。
假设您需要以编程方式创建5个TextView:
int N = 5;
List<TextView> list = new ArrayList<TextView>(N);
for (int i = 0; i < N; i++) {
TextView t = new TextView(this);
t.setText("Textview number: " + i); //customize as you wish
list.add(t);
}
顺便说一句,我看到你在那里做了很多String连接。 使用StringBuilder添加所有字符,然后使用toString()生成最终字符串一次会快得多。