如何为每行设置不同的颜色?数据从SQLite
到table layout
,行数不固定。我想将第一行设置为green
,将第二行设置为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)
可能有一个更好的解决方案,但我想这可行:
// 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;
}
}