Android Custom View 102
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.
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.
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.
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?
Just finished writing a custom layout to display tags and alike views. Not super polished but can be used as a reference.
Source Code