android - 自定义视图 custom view
访问量: 2180
参考:https://stackoverflow.com/documentation/android/1446/creating-custom-views#t=201709020218142901513
关于3 个constructor的解释,见 : https://stackoverflow.com/questions/9195713/do-i-need-all-three-constructors-for-an-android-custom-view
1. 建立xml (非常简单)
<com.yunbi.SmileyView android:layout_height="match_parent" android:layout_width="match_parent" />
2. 建立对应的class . 这里注意: 3个constructor,三个参数的很少用(用于为所有的view统一设置style) , 二个参数的用于通过XML来 inflate , 一个参数的用于使用代码来创建, onMeasure, onDraw必须都在。
package com.yunbi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; /** */ public class SmileyView extends View { Paint circle; float centerX; float centerY; float radius; public SmileyView(Context context) { this(context, null, 0); } public SmileyView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SmileyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaints(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ int w = MeasureSpec.getSize(widthMeasureSpec); int h = MeasureSpec.getSize(heightMeasureSpec); int size = Math.min(w, h); setMeasuredDimension(size, size); } @Override protected void onDraw(Canvas canvas){ canvas.drawCircle(centerX, centerY, radius, circle); } private void initPaints(){ circle = new Paint(Paint.ANTI_ALIAS_FLAG); circle.setStyle(Paint.Style.FILL); circle.setColor(Color.YELLOW); } @Override protected void onSizeChanged(int w, int h ,int oldW, int oldH){ centerX = w / 2f; centerY = h / 2f; radius = Math.min(w, h ) / 2f; } }