2015-10-15 127 views
-1

如何爲每一行設置不同的顏色?數據從SQLite獲得至table layout,並且行數不固定。我想的第一行第三行重新設置爲​​,第二至red,以red ...我已經宣佈color.xml的顏色,但他們沒有工作...如何爲每一行設置不同的顏色

DisplayData.java

// outer for loop 
for (int i = 0; i < rows; i++) { 

    TableRow row = new TableRow(this); 
    row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 
      ViewGroup.LayoutParams.WRAP_CONTENT)); 

    // inner for loop 
    for (int j = 0; j < cols; j++) { 

     TextView tv = new TextView(this); 
     tv.setLayoutParams(new TableRow.LayoutParams(
       ViewGroup.LayoutParams.WRAP_CONTENT, 
       ViewGroup.LayoutParams.WRAP_CONTENT 
     )); 
     // tv.setBackgroundResource(R.drawable.cell_shape); 
     tv.setGravity(Gravity.CENTER); 
     tv.setTextSize(18); 
     tv.setPadding(0, 5, 0, 5); 

     tv.setText(c.getString(j)); 

     row.addView(tv); 
     row.setBackgroundResource(R.drawable.color); 

     row.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       Intent intent = new Intent(DisplayData.this, UpdatePage.class); 
       intent.putExtra("name", name2); 
       intent.putExtra("date",date2); 
       startActivity(intent); 
      } 
     }); 

    } 

    c.moveToNext(); 

     table_layout.addView(row); 


    } 
    sqlcon.close(); 
} 

    } 

color.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <resources xmlns:android="http://schemas.android.com/apk/res/android"> 
     <color android:name="green">#00ff00</color> 
     <color android:name="red">#FF0000</color> 
    </resources> 

</LinearLayout> 
+0

爲什麼不只是保留一個變量並設置顏色? –

+0

對不起,能否詳細說明? – John

+1

爲什麼在LinearLayout中有顏色定義? – traninho

回答

0

有可能是一個好得多的解決方案,但我想這可能是工作:

// outer for loop 
    int colorIndex = 0; 

    for (int i = 0; i < rows; i++) { 

     if (index == 0) 
     { 
      //set background 
      row.setBackgroundColor(getResources().getColor(R.color.some_color)); 
      index++; 
     } 

     else if (index == 1) 
     { 
      //set background 
      row.setBackgroundColor(getResources().getColor(R.color.some_other_color)); 
      index++; 
     } 
     if (index == 2) 
     { 
      //set background 
      row.setBackgroundColor(getResources().getColor(R.color.yet_another_color)); 
      index = 0; 
     } 
} 
+0

R.color.some_other_color?不是「綠色」,「紅色」......? – John

+0

您也可以使用系統顏色,例如: row.setBackgroundColor(Color.GREEN); –

相關問題