官术网_书友最值得收藏!

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:

  1. Create a new class that extends View.
  2. Create custom constructor(s).
  3. Override onMeasure(), and the default implementation returns a size of 100 x 100.
  4. Override onDraw(), and the default implementation draws nothing.
  5. Define custom methods and listeners (such as on<Event>()).
  6. 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:

  1. 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.
  2. Change the class constructor so it extends View. It should look as follows:
    public class CustomView extends View {
  3. Define a Paint object for the class, which will be used in the onDraw():
    final Paint mPaint = new Paint();
  4. 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);
    }
  5. 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();
    }
  6. Finally, inflate our custom view in MainActivity.java by replacing the setContentView() with our view, as shown:
    setContentView(new CustomView(this));
  7. 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

主站蜘蛛池模板: 阳西县| 兴隆县| 珲春市| 全椒县| 云霄县| 工布江达县| 恩施市| 英山县| 天祝| 抚顺市| 巴彦淖尔市| 厦门市| 湾仔区| 屏边| 旬阳县| 黑水县| 余干县| 鄂州市| 兴化市| 河西区| 鹤山市| 房产| 丰顺县| 都匀市| 海兴县| 灵寿县| 柳河县| 巫溪县| 阿拉善左旗| 鄂州市| 卢湾区| 奎屯市| 留坝县| 常德市| 湘潭市| 华安县| 永登县| 八宿县| 龙陵县| 武宁县| 沈阳市|