在Android中,设置ListView控件的分割线,是再平常不过的一件事,一般我们只需要在layout定义的时候,直接设置属性就可以了,如下:
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#fff2f2f2"/>复制代码
就可以得到一个分割线色值为#fff2f2f2的ListView了。
那么,如果需要在代码里动态设置这个ListView的divider颜色怎么办呢。查看ListView的方法可以知道,有一个setDivider方法是用来设置分割线的,不过它的形参是Drawable类型,而不是我们常见int型色值。
把色值转换成Drawable也简单,我们只要用到ColorDrawable,也就是一个纯色的Drawable,于是,代码设置分割线就是这样:
mListView.setDivider(new ColorDrawable(Color.parse("#fff2f2f2")));复制代码
大功告成,一运行,咦,我分割线呢,我那浅浅颜色的分割线呢?
可能是色值太淡了,我干脆把色值设置成黑色,结果还是没有。
好吧,直接看源码,setDivider方法没准不是设置分割线的呢。
/**
* Sets the drawable that will be drawn between each item in the list.
* <p>
* <strong>Note:</strong> If the drawable does not have an intrinsic
* height, you should also call {@link #setDividerHeight(int)}.
*
* @param divider the drawable to use
* @attr ref R.styleable#ListView_divider
*/
public void setDivider(@Nullable Drawable divider) {
if (divider != null) {
mDividerHeight = divider.getIntrinsicHeight();
} else {
mDividerHeight = 0;
}
mDivider = divider;
mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
requestLayout();
invalidate();
}复制代码
也就是说,我们传入的ColorDrawable,不仅把色值传入了,还把高度传入了作为分割线的高度,那么ColorDrawable的getIntrinsicHeight方法返回的高度是什么呢?
查看ColorDrawable源码,里面并没有这个getIntrinsicHeight方法,这个方法是在它的父类Drawable中定义的:
/**
* Returns the drawable's intrinsic height.
* <p>
* Intrinsic height is the height at which the drawable would like to be
* laid out, including any inherent padding. If the drawable has no
* intrinsic height, such as a solid color, this method returns -1.
*
* @return the intrinsic height, or -1 if no intrinsic height
*/
public int getIntrinsicHeight() {
return -1;
}复制代码
如此,setDivider传入ColorDrawable实例的时候,dividerHeight就自然被置为-1了,于是,你的分割线就不见鸟。
所以,解决办法就如setDivider方法的注释上所写,在调用setDivider后再记得调用setDividerHeight来设置分割线高度,就可以展现出来分割线了。
有时候源代码作者的思路是有些Amazing的。