To customize an Android control

  • 2021-10-25 08:03:35
  • OfStack

Original intention of learning: In the actual development process, the original Android controls can no longer meet the actual functional requirements, and some applications need a unique display effect, so we need custom controls to customize controls to meet our needs.

To customize a control

Step 1: First, create a new class CustomView that inherits from View

public class CustomView extends View{}
Step 2: Add a constructor, using the same constructor with AttributeSet parameters

public CustomView(Context context,AttributeSet attrs){
  //Attribute Attributes, custom attributes set in the layout file 
  //attrs It must be passed to the parent class so that the parent class knows the specific parameters to draw 
  super(context,attrs);
}
Step 3: Draw the interface and override the onDraw () method

@Override
protected void onDraw(Canvas canvas){
  // Painting background , New 1 Brushes 
  Paint pain=new Paint();
  paint.setTextSize(48);
  paint.setColor(Color.RED);
  // To create a rectangle, you need to 1 The width and height of a rectangle, viewWidth,viewHeight The value of is obtained by the following steps 
  Rect rect=new Rect(0,0,viewWidth,viewHeight);
  // Draw 1 Rectangles with the parameters of rectangle object and brush object 
  canvas.drawRect(rect,paint);
}
Step 4: Get the width and height of 1 interface

int viewHeight,viewWidth;
@Override
protected void onSizeChanged(int w,int h,int oldw,int oldh){
  // When the interface changes, that is, when cutting the screen, the current width and height 
  super.onSizeChanged(w,h,oldw,oldh);
  viewHeight=h;
  viewWidth=w;
}

The final result is a picture with a red background

Summarize


Related articles: