Class Dimension for java on android

半腔热情 提交于 2019-11-28 11:22:59

You can choose one of these options:

  1. android.util.Size (since API 21). It has getWidth() and getHeight() but it's immutable, meaning once it's created you can't modify it.

  2. android.graphics.Rect. It has getWidth() and getHeight() but they're based on internal left, top, right, bottom and may seem bloated with all its extra variables and utility methods.

  3. android.graphics.Point which is a plain container, but the name is not right and it's main members are called x and y 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;
    

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.

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));
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!