自定义系统控件

tech2024-05-31  72

package com.example.test; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatButton; public class MyButton extends AppCompatButton { Paint paint1 ,paint2; public MyButton(Context context) { super(context); initView(); } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public MyButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { paint1 = new Paint(); paint1.setColor(getResources().getColor(android.R.color.holo_orange_light)); paint1.setStyle(Paint.Style.FILL); //实心 paint2 = new Paint(); paint2.setColor(getResources().getColor(android.R.color.holo_blue_bright)); paint2.setStyle(Paint.Style.STROKE); //空心 } /* * 程序调用super.onDraw(canvas);实现原生控件的功能,我们可以在其前后设计自己的控件*/ @Override protected void onDraw(Canvas canvas) { //调用父类方法前,实现自己的逻辑, //四个实心圆 canvas.drawCircle(0,0,30,paint1); canvas.drawCircle(0,getHeight(),30,paint1); canvas.drawCircle(getWidth(),0,30,paint1); canvas.drawCircle(getWidth(),getHeight(),30,paint1); //三个空心圆 canvas.drawCircle(getWidth()/2,getHeight()/2,getWidth()/8,paint2); canvas.drawCircle(getWidth()/2,getHeight()/2,getWidth()/6,paint2); canvas.drawCircle(getWidth()/2,getHeight()/2,getWidth()/4,paint2); //设置背景 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(getResources().getDrawable(R.color.colorAccent)); } canvas.save(); //保存画布 super.onDraw(canvas); //父类方法 //调用父类方法后,实现自己的逻辑 canvas.restore(); //合并图像 } }

 

xml中引用

<com.example.test.MyButton android:id="@+id/main_my_btn_expendView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ExpendView1" android:textAllCaps="false" android:layout_margin="10dp" />

运行效果如下:

 

参考链接

https://blog.csdn.net/jinmie0193/article/details/80777331?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param

最新回复(0)