Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Last active May 4, 2018 06:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anzfactory/44a67cc392895e9412a1 to your computer and use it in GitHub Desktop.
Save anzfactory/44a67cc392895e9412a1 to your computer and use it in GitHub Desktop.
縦(あるいは横)にあわせる形で正方形にするView
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SquareView">
<attr name="adjust_width" format="boolean"></attr>
</declare-styleable>
</resources>
public class SquareView extends View {
private boolean mAdjustWidth;
public SquareView(Context context) {
super(context, null);
}
public SquareView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SquareView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mAdjustWidth = false;
if (attrs != null) {
TypedArray attrsArray = context.obtainStyledAttributes(attrs, R.styleable.SquareView);
mAdjustWidth = attrsArray.getBoolean(R.styleable.SquareView_adjust_width, false);
attrsArray.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int sideLength = 0;
if (mAdjustWidth) {
// 横幅に合わせる
sideLength = getMeasuredWidth();
} else {
// 縦幅に合わせる
sideLength = getMeasuredHeight();
}
setMeasuredDimension(sideLength, sideLength);
}
public void setAdjustWidth(boolean adjustWidth) {
mAdjustWidth = adjustWidth;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment