Updated 2 December 2020
Custom View
The most important use of custom view is its appearance . Android gives us a bunch of predefined Views, which we can use to build our apps.
But we can also create our own custom Views that can show custom drawings. This is especially useful for things like visualisations and games.
To create our own view, we create a subclass of the View
 class. The basics look like this:
1 2 3 4 5 |
public class CustomView extends View { public CustomView(Context context, AttributeSet attr) { super(context); } } |
View
, we can use it just like any other View
. For example we can use it in our layout XML file:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <view class="com.example.customdrawing.CustomView" id="@+id/custom-view-id" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
In CustomView we create instance of Paint class
1 2 |
Paint paint=new Paint(); paint.setColor(Color.rgb(255, 0, 0)); |
Override onDraw()
The most important step in drawing a custom view is to override the onDraw() method. The parameter onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).
Before you can call any drawing methods, though, it’s necessary to create a Paint object. The next section discusses Paint in more detail.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@Override protected void onDraw(Canvas canvas){ canvas.drawColor(Color.rgb(55,55,55)); Paint redPaint = new Paint(); redPaint.setColor(Color.rgb(255, 0, 0)); Paint whitePaint = new Paint(); whitePaint.setColor(Color.WHITE); Paint bluePaint = new Paint(); bluePaint.setColor(Color.rgb(0, 0, 255)); canvas.drawCircle(700, 500, 200, redPaint); canvas.drawLine(0,0,800,800,whitePaint); canvas.drawCircle(325, 600, 300, bluePaint); } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.