how to set background color for all elements of ListView on OnItemClick event?
I have a ListView and posibility to select one element (single choice).
How can I set background color for all elements of ListView (maybe which are visible at least) when some item was selected?
adapter = new ArrayAdapter(activity, simple_list_item_single_choice, orderlines) { @Override public View getView(final int position, View convertView, final ViewGroup parent) { ... convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { convertView.setBackgroundColor(BLACK); // so here currently selected element is set to BLACK, but also other elements have to be set to WHITE } }); return convertView; } }
Thanks
I don't have much code for you because I'm not at my workstation right now, but I'm thinking you can just set the background of the selected item to black by via your onItemClick as you've already suggested. Cool.
To change the color of the other(unselected) views when a particular view is selected, I'm guessing you can call your Adapter's getCount() and loop through that list, make a call to getChildAt(i) of your ListView. This returns a View which you can call setBackgroundColor(Color) on. Hope this helps
You can do
parent.setBackgroundColor(BLACK);
this.notifyDataSetChanged();
to set your list view background.
I would use a Drawable selector.
Check this link for a pretty good example: http://www.charlesharley.com/2012/programming/custom-drawable-states-in-android/
Basically you create the XML drawable which contains a mapping (which the system uses automatically) to what you would like displayed when certain click events occur.
You can assign the background drawable to any view, so you could do it in your XML for your adapter, or in Java code. Which in your case might be something like this:
convertView.setBackgroundDrawable(R.drawable.MySelector);
链接地址: http://www.djcxy.com/p/50602.html