开发androidkotlinkotlin安卓:每天一个组件:自定义组件❄️2winter2019-08-192019-08-19自定义组件:需要继承View类,重写部分方法 12345678910111213141516171819202122232425 自定义:class myView: View{ private var paint = Paint()//画笔对象 private var H = 54F//高度 private var W = 54F//宽度 constructor(context: Context):super(context)//初始化构造器 constructor(context:Context,set:AttributeSet):super(context,set)//初始化次构造器 var context2 = context override fun onDraw(canvas: Canvas?) {//重写onDraw super.onDraw(canvas) paint.color = Color.RED canvas!!.drawCircle(W,H,15F,paint)} override fun onTouchEvent(event: MotionEvent?): Boolean {//重写触控事件 H = event!!.y W = event.x Toast.makeText(context2,"X:${event.x},Y:${event.y}",Toast.LENGTH_SHORT).show() invalidate()//通知组件重绘 return true }}实例化:val myView = myView(this)//实例化自定义组件layout.addView(myView)//加载进布局 以编程的方式创建组件: 123456789101112131415161718191.1编程的方法创建UIclass MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val layout = LinearLayout(this)//动态创建layout super.setContentView(layout)//设置layout显示 layout.orientation = LinearLayout.VERTICAL//设置方向 val btn = Button(this)//实例化btn对象 btn.setOnClickListener{//设置按钮建监听器 Toast.makeText(this,"我是动态创建的按钮",Toast.LENGTH_SHORT).show() } btn.text = "我是按钮"//设置按钮文本 //设置按钮长宽 btn.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT) layout.addView(btn)//添加按钮进layout }}