Android Custom View 102

Guowei Lv

1 minute read

In this tutorial let’s see how to draw a piechart. class PieChart @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) val bounds: RectF = RectF() val RADIUS = dp2px(150) val OFFSET = dp2px(50) var offsetIndex = 2 val angles = arrayOf(60.0f, 120.0f, 30.0f, 150.0f) val colors = arrayOf("#07004d", "#2d82b7", "#42e2b8", "#f3dfbf") override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.

Android Custom View 102 (Part 13)

Draw a dashboard meter

Guowei Lv

2 minute read

Today let’s draw a dashboard meter. I have drawn the blueprint this time:

Here is the code: class Dashboard @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val BOTTOM_ANGLE = 120 private val RADIUS = dp2px(150) private val ARM_LENGTH = dp2px(120) private val DASH_WIDTH = dp2px(2) private val DASH_LENGTH = dp2px(10) private val DASH_NUM = 12 private val paint = Paint(Paint.

Guowei Lv

5 minute read

Let’s build a sliding menu from scratch by hand. First a glimpse of what the final result looks like.

Step 1: Horizontal Scroll View The secret is that this is just a customized HorizontalScrollView: class SlidingMenu @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : HorizontalScrollView(context, attrs, defStyleAttr) { … } The view can be divided into 2 parts: menu view and content view, and they are just put next to each other.

Android Custom View 102 (Part 11)

Touch event dispatching

Guowei Lv

3 minute read

It is interesting how Android view’s touch events are dispatched. Let’s explore it. Firstly, write a custom view and override its onTouchEvent() method. class TouchView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { override fun onTouchEvent(event: MotionEvent): Boolean { Log.d("TAG", "TouchView - onTouchEvent - ${event.action}") return super.onTouchEvent(event) } } Then, in MainActivity, on the view, call setOnTouchListener() and setOnClickListener(). class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?