Draw a border using a custom Android view

I am trying to create a custom border by creating a custom view. Here is an example of one side of the border:

package com.sparkydev.guessaphrase; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; import android.util.AttributeSet; import android.view.View; public class LeftBorder extends View { private ShapeDrawable vertRect, horizRect; public LeftBorder(Context context, AttributeSet attributeset) { super(context, attributeset); int width = this.getWidth(); int height = this.getHeight(); vertRect = new ShapeDrawable(new RectShape()); vertRect.getPaint().setColor(Color.RED); vertRect.setBounds(0, 0, width/10, height); horizRect = new ShapeDrawable(new RectShape()); horizRect.getPaint().setColor(Color.RED); horizRect.setBounds(0, 0, width, height/9); } protected void onDraw(Canvas canvas){ vertRect.draw(canvas); horizRect.draw(canvas); } } 

And the other side is defined in much the same way. XML is defined as such:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/wallpaper"> <!-- Declares left border position, which is drawn programmatically.--> <com.sparkydev.guessaphrase.LeftBorder android:id="@+id/leftborder" android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <!-- Used a FrameLayout to contain the menu buttons.--> <FrameLayout android:id="@+id/FrameLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content" > <!-- Menu buttons --> </FrameLayout> <!-- Declares right border position (on right of screen, below the left border) --> <com.sparkydev.guessaphrase.RightBorder android:layout_alignParentRight="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/leftborder" /> </RelativeLayout> 

The problem is that borders are not displayed at all. The background shows, but nothing more.

+4
source share
1 answer

From the guide for creating custom components , when creating a custom view, it will have a specified size of 100x100, unless you specify otherwise, see if this is due to the problem you are seeing.

"You almost certainly want to override onMeasure() , and you might also need to override onDraw() if you want the component to show something. Although both have a default behavior, the default onDraw() do nothing, and by default onMeasure() will always set the size to 100x100 - this is probably not what you want.

+10
source

All Articles