Android Custom Component View w/Rounded Corners -


i'm trying create view rounded corners (and background color of choice) can reuse different background colors; hard explain, here's code:

/app/src/com/packagename/whatever/customdrawableview.java

 package com.packagename.whatever;  import android.content.context; import android.content.res.typedarray; import android.graphics.canvas; import android.graphics.drawable.paintdrawable; import android.util.attributeset; import android.view.view;  public class customdrawableview extends view {     private paintdrawable mdrawable;     int radius;      private void init(attributeset attrs) {         typedarray = getcontext().obtainstyledattributes(attrs,r.styleable.roundedrect);         radius = a.getinteger(r.styleable.roundedrect_radius, 0);     }      public customdrawableview(context context, attributeset attrs) {         super(context, attrs);         init(attrs);          mdrawable = new paintdrawable();     }      protected void ondraw(canvas canvas) {         mdrawable.setcornerradius(radius);         mdrawable.draw(canvas);     } } 

here's xml display custom component: /app/res/layout/test.xml

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:ny="http://schemas.android.com/apk/res/com.packagename.whatever"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:background="#ffffff"     android:padding="10dp">      <com.packagename.whatever.customdrawableview         android:id="@+id/custom"         android:layout_width="200dp"         android:layout_height="200dp"         android:background="#b80010"         ny:radius="50"     />  </linearlayout> 

i'm wanting red box have 50px rounded corners, you'll see, not:

red box without rounded corners

the idea change background color in xml , automatically have nice view rounded corners, without having create multiple drawables.

thanks help!

you need set corner radius , color background drawable.

here 1 way work. grab color set in android:background, use create new drawable set background in constructor. work long set android:background color value.

   public customdrawableview(context context, attributeset attrs) {         super(context, attrs);         init(attrs);          // pull out background color         int color = attrs.getattributeintvalue("http://schemas.android.com/apk/res/android", "background", 0xffffffff);          // create new background drawable, set color , radius , set in place         mdrawable = new paintdrawable();         mdrawable.getpaint().setcolor(color);         mdrawable.setcornerradius(radius);         setbackgrounddrawable(mdrawable);     } 

if override ondraw, make sure call super.ondraw(canvas) first background drawn.


Comments