- 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.
- Drupal 8 Blueprints
- C#編程入門指南(上下冊)
- C++ Builder 6.0下OpenGL編程技術(shù)
- 編寫高質(zhì)量代碼:改善Python程序的91個建議
- Building a Recommendation Engine with Scala
- Python應(yīng)用輕松入門
- IBM Cognos Business Intelligence 10.1 Dashboarding cookbook
- Canvas Cookbook
- GameMaker Essentials
- Instant Debian:Build a Web Server
- 寫給大家看的Midjourney設(shè)計書
- Java7程序設(shè)計入門經(jīng)典
- Mastering Concurrency in Python
- Mastering Leap Motion
- 網(wǎng)絡(luò)綜合布線與組網(wǎng)實戰(zhàn)指南