- Android Application Development Cookbook(Second Edition)
- Rick Boyer Kyle Mew
- 782字
- 2025-04-04 20:05:05
Creating a custom component
As we have seen in previous recipes, the Android SDK provides a wide range of components. But what happens when you can't find a prebuilt component that fits your unique needs? You can always create your own!
In this recipe, we will walk through creating a custom component that derives from the View class, just like the built-in widgets. Here's a high-level overview:
- Create a new class that extends View.
- Create custom constructor(s).
- Override
onMeasure()
, and the default implementation returns a size of 100 x 100. - Override
onDraw()
, and the default implementation draws nothing. - Define custom methods and listeners (such as on<Event>()).
- Implement custom functionality.
Tip
While overriding onMeasure()
and onDraw()
is not strictly required, the default behavior is likely not what you would want.
Getting ready
Start a new project in Android Studio and call it CustomView
. Use the default wizard options, including the Phone & Tablet SDK and select Empty Activity when prompted for the Activity type. Once the project files are created and open in Android Studio, you are ready to begin.
How to do it...
We will create a new class for our custom component to derive from the Android View class. Our custom component could be a subclass of an existing class, such as the Activity, but we will create it in a separate file to make it easier to maintain. Here are the steps:
- Start by creating a new Java class and also call it
CustomView
. This is where we will implement our custom component, as described in the introduction. - Change the class constructor so it extends View. It should look as follows:
public class CustomView extends View {
- Define a
Paint
object for the class, which will be used in the onDraw():final Paint mPaint = new Paint();
- Create a default constructor, which requires the activity
Context
, so we can inflate the view. We will set the paint properties here as well. The constructor should look as follows:public CustomView(Context context) { super(context); mPaint.setColor(Color.BLACK); mPaint.setTextSize(30); }
- Override the onDraw() method as follows:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); setBackgroundColor(Color.CYAN); canvas.drawText("Custom Text", 100, 100, mPaint); invalidate(); }
- Finally, inflate our custom view in
MainActivity.java
by replacing thesetContentView()
with our view, as shown:setContentView(new CustomView(this));
- Run the application on a device or emulator to see it in action.
How it works...
We start by extending the View class, just as the built-in components do. Next, we create the default constructor. This is important as we need the context to pass down to the super class, which we do with the call:
super(context);
We need to override onDraw()
, otherwise, as mentioned in the introduction, our custom view won't display anything. When onDraw()
is called, the system passes in a Canvas object. The canvas is the area of the screen for our view. (Since we didn't override onMeasure()
, our view would be 100 x 100, but since our entire activity consists of just this view, we get the whole screen as our canvas.)
We created the Paint
object at the class level, and as final
, to be more efficient with memory allocation. (onDraw()
should be as efficient as possible since it can be called multiple times per second.) As you see from running the program, our onDraw() implementation just sets the background color to cyan and prints text to the screen (using drawText()
).
There's more...
Actually, there's a lot more. We've just touched the surface of what you can do with a custom component. Fortunately, as you see from this example, it doesn't take a lot of code to get basic functionality. We could easily spend an entire chapter on topics such as passing layout parameters to the view, adding listener callbacks, overriding onMeasure()
, using our view in the IDE, and so on. These are all features you can add as your needs dictate.
While a custom component should be able to handle any solution, there are other options that might require less coding. Extending an existing widget is often sufficient without the overhead of a custom component from scratch. If what you need is a solution with multiple widgets, there's also the compound control. A compound control, such as a combo box, is just two or more controls grouped together as a single widget.
A compound control would generally extend from a layout, not a View, since you will be adding multiple widgets. You probably wouldn't need to override onDraw() and onMeasure(), as each widget would handle the drawing in their respective methods.
See also
- For more information on drawing, look at Chapter 9, Graphics and Animation. For full details on the View object, refer to the Android Developer resource at: http://developer.android.com/reference/android/view/View.html