I am adding simple data into a listview (name and time) and I want to be able to alternate between a white and grey background for each table row. I am currently setting the background color in the xml file.
I am using the code from http://saigeethamn.blogspot.com/2010/04/custom-listview-android-developer.html
Thanks
EDIT my code looks like this
//R.layout.custom_list_view is just a list view with grey background
//(I want it white for every other one)
//On Create section
setContentView(R.layout.custom_list_view);
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.custom_row_view,
new String[] {"pen","price"},
new int[]开发者_Python百科 {R.id.text1,R.id.text2}
);
//see function below
populateList();
setListAdapter(adapter);
}
static final ArrayList<HashMap<String,String>> list =
new ArrayList<HashMap<String,String>>();
private void populateList() {
//for loop would go here
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen","MONT Blanc");
temp.put("price", "200.00$");
list.add(temp);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("pen","Parker");
temp2.put("price", "400.00$");
list.add(temp2);
//theres no place to change the background of my listview
Final Edit. Here is an easy solution http://ykyuen.wordpress.com/2010/03/15/android-%E2%80%93-applying-alternate-row-color-in-listview-with-simpleadapter/ Change SimpleAdapter adapter to the custom SpecialAdapter found in the website. Thank you all for helping
You should do implement custom adapter and set background color there:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View convertViews;
if (convertView == null) {
convertViews = mInflater.inflate(R.layout.startingsquadlistview, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.textview);
convertViews.setTag(holder);
} else {
convertViews = convertView;
holder = (ViewHolder) convertViews.getTag();
}
if(position % 0) {
convertView.setBackground(context.getResources().getColor(R.color.col1);
else
convertView.setBackground(context.getResources().getColor(R.color.col2);
return convertViews;
}
You could create a custom list adapter and in there create a global boolean variable called 'alternateColor'. Then in your getView() function put this (in this case 'tv' is your textview):
if (alternateColor)
{
tv.setBackgroundColor(Color.GRAY);
alternateColor = false;
}
else if (!alternateColor)
{
tv.setBackgroundColor(Color.WHITE);
alternateColor = true;
}
Click here for a tutorial on how to make a custom list adapter.
精彩评论