- Building Android UIs with Custom Views
- Raimon Ràfols Montané
- 217字
- 2021-07-02 15:33:37
Creating a simple view from scratch
Now that we've seen how to modify an already existing View, we'll see a more complex example: how to create our own custom view from scratch!
Let's start by creating an empty class that extends from View:
package com.packt.rrafols.customview; import android.content.Context; import android.util.AttributeSet; import android.view.View; public class OwnCustomView extends View { public OwnCustomView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } }
We will now add the same code as the previous example to draw a red background:
package com.packt.rrafols.customview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class OwnCustomView extends View { private Paint backgroundPaint; public OwnCustomView(Context context, AttributeSet attributeSet) { super(context, attributeSet); backgroundPaint= new Paint(); backgroundPaint.setColor(0xffff0000); backgroundPaint.setStyle(Paint.Style.FILL); } @Override protected void onDraw(Canvas canvas) { canvas.drawRect(0, 0, getWidth(), getHeight(),
backgroundPaint); super.onDraw(canvas); } }
If we run the application, as we can see in the following screenshot, we'll have a slightly different result from the previous example. This is because in our previous example the TextView widget was resizing to the size of the text. If we remember correctly, we had android:layout_width="wrap_content" and android:layout_height="wrap_content" in our layout XML file. This new custom view we've just created doesn't know how to calculate its size.

Check the Example02 folder in the GitHub repository for the full implementation of this simple example.