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

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.

主站蜘蛛池模板: 青河县| 平塘县| 涪陵区| 高密市| 彭州市| 烟台市| 曲松县| 仪征市| 绥芬河市| 白沙| 常山县| 富锦市| 鄄城县| 乌恰县| 河南省| 兴仁县| 宁陕县| 尚义县| 淮滨县| 青州市| 信阳市| 调兵山市| 台中市| 博罗县| 宁都县| 江达县| 斗六市| 乌鲁木齐县| 张家港市| 宣武区| 宿迁市| 迭部县| 通山县| 日喀则市| 田阳县| 荔浦县| 吉木乃县| 新疆| 庄河市| 新民市| 来凤县|