Translate

Friday, February 1, 2013

Draw Shapes using XML

we can draw the Shape using ShapeDrawable class . I've here Created a class which Inherited View Class. We can do View our shape using setContentView() Method. we can call our view(shape) inside that method using xml or java Lets Start to do one by one , Now we need to create our view,
package com.example.drawwithxml;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {
private ShapeDrawable mDrawable;

public MyView(Context context,AttributeSet a) {
super(context,a);

int x = 10;
int y = 10;
int width = 300;
int height = 50;

mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}

protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}

onDraw() method is very Important. without this method ,we create the shape .but can't view(shape will be invisible). The Constructor must be public MyView(Context context,AttributeSet a) which has AttribubeSet as its parameter because we're defining MyView Class in xml with some attributes we desired. After Creating View we call this view @ setContentView(R.layout.main) (using xml ). the xml file will be ,


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

   <com.example.rakeshdraw.MyView
   android:layout_width="fill_parent"  
android:layout_height="fill_parent"  
 android:id="@+id/custom_drawable_view"
/>

</RelativeLayout>



 we're calling this xml in the following Java file ,


package com.example.drawwithxml;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
MyView mCustomDrawableView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //mCustomDrawableView=new MyView(this);
        setContentView(R.layout.main);
    }
}

If you don't like to use xml means, *uncomment the above java file. * use public MyView(Context context) constructor in MyView Class. *change setContentView(R.layout.main) to setContentView(mCustomDrawableView). thats all :) Wanna have Full Source Code? Click Here

No comments:

Post a Comment