2012-07-25 101 views
-1

我正在製作應用程序,將結果存儲在多個文字瀏覽中, 首先,我需要獲取視圖,它們是20個視圖,分別命名爲result 1,.... result 20. 我怎麼能讓他們獲得一個textview數組。 我發現這個方法,但如果你有一個句柄父包含文本視圖的佈局,您可以遞歸有了這樣的功能,發現他們這是太長獲取TextViews數組

TextView [] results = {(TextView)findViewById (R.id.result1), 
      (TextView)findViewById (R.id.result2),(TextView)findViewById (R.id.result3), 
      (TextView)findViewById (R.id.result4),(TextView)findViewById (R.id.result5), 
      (TextView)findViewById (R.id.result6).....}; 

謝謝大家幫忙

+0

什麼是 「它太長時間」 呢?太久了? – Kaediil 2012-07-25 15:25:36

+0

我需要編寫一個非常大的代碼,因爲我只有20個textview,並且我有3個佈局。 – Abol3z 2012-07-25 15:31:24

+0

沒有其他辦法。您可能會考慮使用ListView而不是多個文字視圖。 – Kaediil 2012-07-25 15:32:16

回答

0

如何開始是正確的,現在考慮將該重複代碼放入循環中。

例如設計一個方法,將輸入一個TextView資源數組,並使用「for」循環通過相應的id查找該視圖。

private TextView[] initTextViews(int[] ids){ 

     TextView[] collection = new TextView[ids.length]; 

     for(int i=0; i<ids.length; i++){ 
      TextView currentTextView = (TextView)findViewById(ids[i]); 
      collection[i]=currentTextView; 
     } 

     return collection; 
} 

然後你使用這樣的:

// Your TextViews ids 
int[] ids={R.id.result1, R.id.result2, R.id.result3}; 

// The resulting array 
TextView[] textViews=initTextViews(ids); 
+0

我認爲這是我應該這樣做的方式 – Abol3z 2012-07-25 15:46:03

+0

我有問題......你怎麼能把R.id.result1作爲一個整數數組的元素? – Abol3z 2012-07-25 15:49:08

+0

只需更改方法的參數以接受整數數組:initTextViews(Integer [] ids)。 然後將您的資源ID也存儲在Integer數組中:Integer [] ids = {R.id.result1,R.id.result2,R.id.result3}; – 2012-07-25 15:51:05

0

void getTextViews(View view, List<TextView> textViews) { 
    if (view instanceof TextView) { 
    textviews.add((TextView)view); 
    else if (TextView instanceof ViewGroup) { 
    getTextViews((ViewGroup)view, textViews); 
    } 
} 

現在這樣稱呼它,

ViewGroup topLayout = findViewById(...); 
List<TextView> views = new ArrayList<TextView>(); 
getTextViews(topLayout, views); 
TextView[] textViewArray = textViews.toArray(new TextView[0]); 

這是相當長的時間,但它具有無需更改代碼(如果添加,刪除或重命名文本視圖)的優勢。

恕我直言,不要着重寫更少的代碼,專注於寫清晰的代碼。你輸入的速度很少是你生產力的限制因素。

+0

不要忘記檢查textviewParent.getChildAt(i)instanceof TextView – 2012-07-25 15:35:09

+0

這是有用的,但我有一個父母每5個textviews 4父母。 – Abol3z 2012-07-25 15:37:07

+0

很好,請參閱編輯。 – 2012-07-25 15:47:34