在我的应用程序中,我有列表,我用数组适配器充气它。一切都很好,我的结果列在清单中。
我喜欢更改列表的背景颜色(例如,行为红色,绿色为奇数行)。
这是我行的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="@+id/rllist"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginBottom="15dip"
>
<TextView
android:id="@+id/outstanding_contractdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="15sp" />
<TextView
android:id="@+id/outstanding_contractno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/outstanding_contractdate"
android:paddingLeft="20dip"
android:textColor="#ffffff"
android:textSize="15sp" />
<TextView
android:id="@+id/outstanding_contractamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textSize="15sp" />
</RelativeLayout>
</LinearLayout>
我写了以下代码:
static class ViewHolder {
RelativeLayout rlList;
TextView tvContDate;
TextView tvContNo;
TextView tvContAmount;
}
在数组适配器中我有这个:
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
View row = convertView;
if(row == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_outstanding, parent, false);
//convertView = mInflater.inflate(R.layout.list_outstanding, parent, false);
holder = new ViewHolder();
holder.rlList = (RelativeLayout) convertView.findViewById(R.id.rllist);
holder.tvContDate = (TextView) row.findViewById(R.id.outstanding_contractdate);
holder.tvContNo = (TextView) row.findViewById(R.id.outstanding_contractno);
holder.tvContAmount = (TextView) row.findViewById(R.id.outstanding_contractamount);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.tvContDate.setText(llData.get(position).split(",")[0].trim());
holder.tvContNo.setText(llData.get(position).split(",")[1].trim());
holder.tvContAmount.setText(llData.get(position).split(",")[2].trim());
if(position%2 != 0)
holder.rlList.setBackgroundColor(0x00FF00);
else
holder.rlList.setBackgroundColor(0XFF0000);
return(row);
}
运行应用程序后,当我到达此代码时,会发生错误。根据LogCat它是“空指针异常”并指向getView()中的这一行:
holder.rlList = (RelativeLayout) convertView.findViewById(R.id.rllist);
似乎一切都好,但我不知道我的问题在哪里?!!!
===========
我已将上述行更改为:
holder.rlList = (RelativeLayout) row.findViewById(R.id.rllist);
现在我有我的结果,但背景没有应用?!!!
答案 0 :(得分:2)
尝试使用
if(position%2 != 0)
holder.rlList.setBackgroundColor(Color.parseColor("#00ff00"));
else
holder.rlList.setBackgroundColor(Color.parseColor("#ff0000"));