androidxmldrawablediagonallayerdrawable

Diagonal line across view


Based on some condition, I have to diagonally cut the list cell. For this I have made diagonal drawable image using this code:

diagonal_line.xml

 <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:top="0dp"
        android:bottom="0dp"
        >
        <rotate
            android:fromDegrees="315"
            android:toDegrees="315"
            android:pivotX="0%"
            android:pivotY="0%" >
            <shape
                android:shape="line"
                >
                <stroke
                    android:width="10dp"
                    android:color="@color/grey" />
            </shape>
        </rotate>
    </item>
    </layer-list>

In list cell's xml it is used as:

 <ImageView 
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@drawable/diagonal_line"
    android:layerType="software"
    android:scaleType="fitXY"
    />

This diagonal line appears in graphics view of cell's xml but not after list is inflated. For now its visbility is independent of any condition i.e. it is visibility is always true.

Any idea where the issue is?


Solution

  • Custom view for diagonal line is:

    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.view.View;
    public class DiagonalLineView extends View {
    
    private int dividerColor;
    private Paint paint;
    
    public DiagonalLineView(Context context)
    {
        super(context);
        init(context);
    }
    
    public DiagonalLineView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context);
    }
    
    public DiagonalLineView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context);
    }
    
    private void init(Context context)
    {
        Resources resources = context.getResources();
        dividerColor = resources.getColor(R.color.grey);
    
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(dividerColor);
             paint.setStrokeWidth(resources.getDimension(R.dimen.vertical_divider_width));
    }
    
    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawLine(0, getHeight(), getWidth(), 0, paint);
    }
    
    }
    

    It worked for me.