Home > android java > Custom widgets

Custom widgets

August 25th, 2009 Leave a comment Go to comments

(Android phone – how-to/example)

If you consider doing your own custom widgets, you must start by creating a new class, that extends android.view.View

The simplest example is customizing a bit the screen layout. Consider you want to draw a frame, on top of an image or the camera preview. In this example you just need to extend View (as mentioned), and than override the onDraw(Canvas canvas) method, where you will be doing your drawing.

public final class CaptureLayout extends View
{
….
@Override
public void onDraw(Canvas canvas)
{
   int width = canvas.getWidth();
   int height = canvas.getHeight();

   // Draw the exterior (i.e. outside the framing rect) darkened
   Paint m_Paint = new Paint();
   m_Paint.setColor(Color.GREEN);
   Rect m_Box = new Rect();
   m_Box.set(0, 0, width, frame.top); // create a box
   canvas.drawRect(m_Box, m_Paint); // draw the box with the given color

If you want more, let’s add some interaction with the widget.
For example let’s say we want to display a message if the user hits the green box (that we just drew).
In order to do this, we need to add a click listener. Thus, when we allocate the widget, we need to pass this click_listener as a parameter to setOnClickListener. Example:

CaptureLayout cl = (CaptureLayout)findViewById(R.id.mezzofanti_capturelayout_view);
cl.setOnClickListener(new OnClickListener() {
     public void onClick(View clickedView) {
     // action for green rectangle pressed
     }
     }
);

Categories: android java Tags:
  1. No comments yet.
  1. No trackbacks yet.