Q:

Android: Making the width and the height of a custom view equal

I am using a custom view (CoordinateGridView) in XML like this:
<com.android.catvehicle.CoordinateGridView
    android:id="@+id/coordinateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

I am trying to get the width of the CoordinateGridView to fill the entire width of the screen. The height should then match the width -- therefore, the custom view should always be drawn as a square.
How do I do this?

A:

Override the onMeasure function in CoordinateGridView:
public void onMeasure(int widthSpec, int heightSpec) {
  super.onMeasure(widthSpec, heightSpec);
  int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
  setMeasuredDimension(size, size);
}

See https://github.com/chiuki/android-square-view for a full example.

