In Monkey Write, the character sits in a square.
Initially I just hard-coded the width to be equal to the height, but I wanted them to scale with the device dimensions.
Today I found an elegant way to do it, with 3 lines of code in my custom View
:
public void onMeasure(int widthSpec, int heightSpec) { super.onMeasure(widthSpec, heightSpec); int size = Math.min(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(size, size); }
Since my class extends View
, I can reuse all the measurement logic by calling super
.
After that, I take the measured width and height, find the smaller one, and use it to set the width to be the same as the height.
I made a sample project to test the SquareView
.
It is set to take one third of the screen width, and the easiest way to try it with different dimensions is to rotate the screen.
Source code: http://github.com/chiuki/android-square-view.
No comments:
Inline coding questions will not be answered. Instead, ask on StackOverflow and put the link in the comment.
Post a Comment