Android Adding Dynamic ListView Header



I have a list view and I am trying to set header for it so that it looks like a table header. Here is the XML file of my list view row:


PS: I have removed some codes to shorten the question



<?xml version="1.0" encoding="utf-8"?>



<TextView
android:id="@+id/txtDisplayDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/txtDisplayCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>


And my XML file of my header list view:



<?xml version="1.0" encoding="utf-8"?>



<TextView
android:id="@+id/txtDisplayDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Date" />
<TextView
android:id="@+id/txtDisplayCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Category" />


And the class where I populate the list view:



private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;

public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
LinearLayout listHeaderView = (LinearLayout)inflater.inflate(
R.layout.trans_header_layout, null);
listview.addHeaderView(listHeaderView);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return _translist.size();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {

convertView = inflater.inflate(R.layout.trans_listview_row,
null);
viewHolder = new ViewHolder();

viewHolder.txt_ddate = (TextView) convertView
.findViewById(R.id.txtDisplayDate);
viewHolder.txt_dcat = (TextView) convertView
.findViewById(R.id.txtDisplayCat);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}

viewHolder.txt_ddate.setText(_translist.get(position).getDate()
.trim());
viewHolder.txt_dcat.setText(_translist.get(position)
.getCategory().trim());
return convertView;
}
}


However, by using these codes, here is the output that I've gotten:


enter image description here


The header does not match with the column below it. I wonder is there any alternate way to add header to list view so that it looks like a table header.


Thanks in advance.


No comments:

Post a Comment