以编程方式在drawable底部绘制水平线

时间:2016-01-23 23:24:00

标签: android listview drawable divider

我必须动态更改listView的分隔颜色。

  1. 溶液:
    因此,我以编程方式创建一个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;
    }
    }
    
  2. 溶液:
    我还尝试使用可绘制的形状作为分隔线并改变其颜色。但我得到以下例外:

    LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable
    
  3. 如何在图层列表中访问笔划?
    这是我的代码:

    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);
    

0 个答案:

没有答案