我必须动态更改listView的分隔颜色。
溶液:
因此,我以编程方式创建一个Drawable绘制一条水平线并将其设置为我的convertView的背景。现在该行位于我的convertView中间。如何将其与底部对齐?
public class DividerView extends Drawable {
private Paint mPaint;
public DividerView() {
mPaint = new Paint();
mPaint.setStrokeWidth(3);
}
@Override
public void draw(Canvas canvas) {
int lvl = getLevel();
Rect b = getBounds();
float x = b.width() * lvl / 10000.0f;
float y = (b.height() - mPaint.getStrokeWidth()) / 2;
mPaint.setColor(Color.BLACK);
canvas.drawLine(x, y, b.width(), y, mPaint);
}
@Override
protected boolean onLevelChange(int level) {
invalidateSelf();
return true;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
溶液:
我还尝试使用可绘制的形状作为分隔线并改变其颜色。但我得到以下例外:
LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable
如何在图层列表中访问笔划?
这是我的代码:
divider.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
</shape>
</item>
<item android:top="-6dp" android:right="-6dp" android:left="-6dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:width="1dp"
android:color="#000000" />
</shape>
</item>
ListAdapter.java
GradientDrawable drawable = (GradientDrawable)convertView.getBackground();
drawable.setStroke(3, Color.RED);
convertView.setBackground(drawable);