簡體   English   中英

Java“ for”循環來填充文本視圖

[英]Java “for” loop to populate textviews

必須有一種更好的方法來執行此操作,但是我嘗試過的所有操作都失敗了。 我不確定,也許我必須以編程方式創建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(...);
}

當然,之后您必須將它們添加到父視圖(活動)中。

希望這可以幫助!

看起來很簡單(如果您需要的話)。

假設您需要以編程方式創建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()僅生成一次最終字符串,會更快得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM