本文共 3004 字,大约阅读时间需要 10 分钟。
1. 需求 :
2. View是如何工作的?
构造器---->初始化
onMesure() 定大小
onLayout() 定位置
onDraw() 绘制
invalidate() 刷新
5.1 添加一个Button组件并设置点击事件
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); } private void initViews() { mButton = findViewById(R.id.customBtn); mButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.customBtn : startActivity(new Intent(MainActivity.this, CustomButtonActivity.class)); break; } }}
5.2 新建一个CustomButtonActivity类和 activity_custombtn.xml文件
public class CustomButtonActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custombtn); }}
5.3 新建一个CustomRedButton类用来设置自定义控件
/** * 需求: * 1、做一个圆形的红色按钮 * 2、中间有一个白色的数字 * 3、数字起始为 20 * 4、每点击一次减少1 */public class CustomRedButton extends View implements View.OnClickListener { private Paint mPaint; private Rect mRect; private int mNumber = 20; public CustomRedButton(Context context) { this(context, null); } public CustomRedButton(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CustomRedButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * init the view * 将 new对象单独拿出来,避免内存的开销 */ private void init() { mPaint = new Paint(); // 创建画笔 mRect = new Rect(); // 创建矩形 this.setOnClickListener(this); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 设置画布为红色 mPaint.setColor(Color.RED); mPaint.setAntiAlias(true);// 消除锯齿 // 绘圆 :drawCircle(x坐标, y坐标, r半径, mPaint画笔) canvas.drawCircle(getWidth()/2, getHeight()/2, getWidth()/2, mPaint); // 中间的白色数字 mPaint.setColor(Color.WHITE); mPaint.setTextSize(60); String text = String.valueOf(mNumber); /* * getTextBounds(文字, 起始值0, 文字的长度, mRect: 是这个数字四周的边距) * */ mPaint.getTextBounds(text, 0, text.length(), mRect); int textWidth = mRect.width(); int textHeight = mRect.height(); canvas.drawText(text, getWidth()/2 - textWidth/2, getHeight()/2 + textHeight/2, mPaint); } @Override public void onClick(View v) { //每点击一次减少1 if (mNumber > 0) { mNumber--; } else { mNumber = 20; } invalidate(); // 刷新 }}
5.4 在 activity_custombtn.xml文件中引用CustomRedButton类
5.5 效果预览
转载地址:http://gziwi.baihongyu.com/