To change the default behaviour of View in Custom View, one need to override onMeasure()
. Depending on how you use your custom view, extend View and modify onMeasure()
as per the requirement.
Layout process consists of two passes, measuring the view and layout the views. Measure pass sets how big the view should be, the dimensions of it, and that the layout pass sets where to place the view, the position of it. The layout part is only interesting for views with children, in other words views that inherits from ViewGroup.
Lets assume that we want Square view. To modify the measuring we override the onMeasure() method. Class MeasureSpec
is used to extract the size and the mode of the integers. There are three modes i.e. UNSPECIFIED
, AT_MOST
and EXACTLY
. So if the size is 200 pixels and the mode is AT_MOST, then the parent says that it’s up to you to decide the size, but you can be at most 300 pixels.
In below example, a relative layout default behaviour is overriden to square layout.
public class SquareLayout extends RelativeLayout { public SquareLayout(Context context) { super(context); } public SquareLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SquareLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSize == 0 && heightSize == 0) { // If there are no constraints on size, let Layout measure super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Now use the smallest of the measured dimensions for both dimensions final int minSize = Math.min(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(minSize, minSize); return; } final int size = Math.min(widthSize, heightSize); final int newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY); super.onMeasure(newMeasureSpec, newMeasureSpec); } }
Layout file using the above custom view is given below
<com.example.testapplication.SquareLayout android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center_horizontal" android:orientation="horizontal" > <ImageView android:id="@+id/cellImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:adjustViewBounds="true" android:padding="2dp" android:scaleType="centerCrop" android:src="@drawable/ic_launcher" /> </com.example.testapplication.SquareLayout>