Last active
May 4, 2018 06:06
-
-
Save anzfactory/44a67cc392895e9412a1 to your computer and use it in GitHub Desktop.
縦(あるいは横)にあわせる形で正方形にするView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="SquareView"> | |
<attr name="adjust_width" format="boolean"></attr> | |
</declare-styleable> | |
</resources> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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