How to draw borders for custom views in Android?
I created a CustomView class that extends from the ViewGroup . My idea is to arrange these CustomViews as cells in a table. I added a TextBlock as a child to each CustomViews and has a variable index to maintain the index of the cell in the table. My requirement is to draw the right and bottom borders for the CustomViews so that it looks like a table. I tried creating xml drawable like /res/drawable/textlines.xml and assigned it as Custom Custom background property.
Here is the code I tried. But this limits all four sides. However, I only need the right and bottom borders. Is there any other way to achieve this?
<item android:right="1dp" android:bottom="1dp">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="@android:color/black" />
<solid android:color="@android:color/transparent" />
</shape>
</item>
It is not recommended to specify the left and top borders as negative. I believe this is not the correct way to achieve this requirement. Please suggest me some workarounds to achieve this.
source to share
If you have a custom view you can override the onDraw line and draw in there. Here's an example:
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor( Color.RED );
paint.setStrokeWidth( 1.5f );
paint.setStyle( Paint.Style.STROKE );
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
source to share
You can add a border on which side you want.In addition, you can control various parameters of each side, such as the color or thickness of the border. An example of adding a border to the right and botoom:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="1dp">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFDDDDDD" />
<solid android:color="#000000" />
</shape>
</item>
<item android:bottom="1dp">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFDDDDDD" />
<solid android:color="#00000000" />
</shape>
</item>
</layer-list>
source to share