2016年8月11日 星期四

How to make a view that layout_height must equal to layout_width ?


32 How to make a view that layout_height must equal to layout_width ?


You can create a custom subclass of Button and override onMeasure, for example:

public class SquareButton extends Button {

   public SquareButton(Context context) {
       super(context);
   }

   public SquareButton(Context context, AttributeSet attrs) {
       super(context, attrs);
   }

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       super.onMeasure(widthMeasureSpec, heightMeasureSpec);
       setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
   }
}




To use SquareButton in your layout file, change your Button declarations to the following:

<your.package.name.SquareButton
   android:id="@+id/photos_photoButton1"
   android:layout_width="[DESIRED WIDTH]dp"
   android:layout_height="0dp"
   android:layout_marginLeft="5dp"
   android:layout_marginRight="5dp"
   />