问题
What is the equivalent form of class java.awt.Dimension
for android?
回答1:
You can choose one of these options:
android.util.Size
(since API 21). It hasgetWidth()
andgetHeight()
but it's immutable, meaning once it's created you can't modify it.android.graphics.Rect
. It hasgetWidth()
andgetHeight()
but they're based on internalleft
,top
,right
,bottom
and may seem bloated with all its extra variables and utility methods.android.graphics.Point
which is a plain container, but the name is not right and it's main members are calledx
andy
which isn't ideal for sizing. However, this seems to be the class to use/abuse when getting display width and height from the Android framework itself as seen here:Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y;
回答2:
You could use Pair<Integer, Integer> which is Android's generic tuple class. (You would need to replace getWidth()
and getHeight()
with first
and second
, though.) In other places of the Android API the Android team seems to use ad-hoc classes for this purpose, for instance Camera.Size.
回答3:
Why do you need to abuse other classes instead of implementing something extremely simple like:
public class Dimensions {
public int width;
public int height;
public Dimensions() {}
public Dimensions(int w, int h) {
width = w;
height = h;
}
public Dimensions(Dimensions p) {
this.width = p.width;
this.height = p.height;
}
public final void set(int w, int h) {
width = w;
height = h;
}
public final void set(Dimensions d) {
this.width = d.width;
this.height = d.height;
}
public final boolean equals(int w, int h) {
return this.width == w && this.height == h;
}
public final boolean equals(Object o) {
return o instanceof Dimensions && (o == this || equals(((Dimensions)o).width, ((Dimensions)o).height));
}
}
来源:https://stackoverflow.com/questions/8876130/class-dimension-for-java-on-android