Android自定义View之正方形

在Android开发中,有时候我们需要实现一个正方形的View,可以在布局中自由使用,并根据实际需求进行定制化。本文将介绍如何使用自定义View的方式来实现一个正方形的View。

前提条件

在开始之前,需要确保你已经熟悉基本的Android开发知识,包括布局和自定义View的基本概念。

步骤

1. 创建自定义View类

首先,我们创建一个自定义View类,继承自View

javaCopy codepublic class SquareView extends View {
          
    public SquareView(Context context) {
          
        super(context);
    }
    public SquareView(Context context, AttributeSet attrs) {
          
        super(context, attrs);
    }
    public SquareView(Context context, AttributeSet attrs, int defStyleAttr) {
          
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
          
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int size = Math.min(width, height);
        setMeasuredDimension(size, size);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

2. 设置布局文件

接下来,在布局文件中引入自定义的SquareView。

xmlCopy code<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.example.app.SquareView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight