2015-10-15 96 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); –

相关问题