How to draw Borders for Custom Views in Android?
android, android-layout, border
Solution
When you have a custom view you can override onDraw and draw line 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);
}
Problem
I have created a CustomView class extending from the ViewGroup. My Idea is to arrange these CustomViews like cells in a table. I have added a TextBlock as child for each CustomViews and have 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 such that it appear like a table. I tried creating an xml drawable such as /res/drawable/textlines.xml and assigned it as my CustomView's background property. Here is the code that I tried. But this draws borders on all four sides. However I need only right and bottom borders alone. 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> ``` Please do not recommend making the left and top borders as negative values. I believe its not the correct way to achieve this requirement. Please suggest me some workarounds to achieve this.