为列表视图中的每个元素设置不同的分隔线颜色 [英] Setting different divider color to each element in list view
问题描述
我想要一个列表,列表元素之间有不同的分隔线.我用这段代码定义了一个高度为 1 的白色分隔线:
I want to have a list with different dividers between the list elements. I have used this code to define a white divider with height 1:
_listView.setDivider(new ColorDrawable(Color.WHITE));
_listView.setDividerHeight(1);
然而,它将所有元素的分隔线设置为白色,我只希望其中一些元素为白色,而其他元素为不同颜色.
However it sets the divider for all the element to be white, and I want only some of them to be white and the other in different color.
我该怎么做?
推荐答案
将分隔线设置为高度为 0 并在您的项目布局中实现一个高度为 1 的视图,并在每次视图时根据列表项更改其颜色已建成.
Set the divider to height to 0 and implement a View in your item layout with the height of 1 and change its color based on the list item every time the view is built.
这是一个 XML 布局示例:
Here's an XML layout sample:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<View
android:id="@+id/divider"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#FFFFFFFF" />
</LinearLayout>
这就是您在适配器中更改颜色的方式:
And this is how you change the color in the adapter:
public class MyAdapter extends BaseAdapter {
/** List of items to show */
private ArrayList<String> items = new ArrayList<String>();
private Context context;
private int color[];
public OffersAdapter(Context c, ArrayList<String> items, int color[])
{
super();
this.context = c;
this.items = items;
this.color = color;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if(null == convertView)
{
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.text = (TextView) convertView.findViewById(R.id.text);
viewHolder.divider = (View) convertView.findViewById(R.id.divider);
convertView.setTag(viewHolder);
} else {
//Retrieve the current view
viewHolder = (ViewHolder) convertView.getTag();
}
//This is where you chance the divider color based on the item
viewHolder.divider.setBackgroundColor(color[position]);
viewHolder.text.setText(items.get(position));
return convertView;
}
//Holds the current view
private static class ViewHolder {
public TextView text;
public View divider;
}
}
其中 int color[]
是您要使用的颜色列表.
Where int color[]
is a list of the colors you want to use.
更多关于ViewHolder 在这里阅读.
这篇关于为列表视图中的每个元素设置不同的分隔线颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!