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

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.

主站蜘蛛池模板: 荣昌县| 正阳县| 古浪县| 通辽市| 沭阳县| 乡宁县| 蒙城县| 关岭| 澳门| 侯马市| 临城县| 延寿县| 积石山| 开远市| 云和县| 台东县| 饶平县| 海门市| 镇原县| 汨罗市| 七台河市| 尖扎县| 正阳县| 昭觉县| 抚顺县| 高尔夫| 宜宾市| 吉木乃县| 泽库县| 曲阳县| 屏东市| 丹东市| 蒲城县| 永清县| 淮北市| 滁州市| 太仆寺旗| 漳州市| 抚松县| 荔波县| 古田县|