Chan Myae Aung
Chan Myae Aung

Reputation: 547

Custom RelativeLayout Border Not Showing

I create a custom RelativeLayout to add a border.But border is not appear. When I add background attribute,the border will appear.When I remove background attributes,border disappear.I want to show border without background attribute. Can anyone explain me how to solve this problem.

Here is my code...

public class BorderRelativeLayout extends RelativeLayout {

Paint paint;
Rect rect;

public BorderRelativeLayout(Context context) {
    super(context);
    init();
}

public BorderRelativeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public void init(){
    paint = new Paint();
    paint.setColor(Color.RED);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(20f);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    rect = new Rect(0,0,getWidth(),getHeight());
    canvas.drawRect(rect,paint);
}

}

Upvotes: 1

Views: 350

Answers (1)

Ben P.
Ben P.

Reputation: 54204

For RelativeLayout, onDraw() isn't called unless you have a background set. So you cannot create a border in this manner.

However, you can add a border to your RelativeLayout much more easily than by creating a custom subclass. Simply create a ShapeDrawable in XML and assign it to your layout.

border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke
        android:width="5dp"
        android:color="#f00"/>

</shape>

layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:textColor="#000"
        android:textStyle="bold"
        android:text="hello world"/>

</RelativeLayout>

enter image description here

Upvotes: 1

Related Questions