0

我检查参考以获得屏幕高度和宽度。我的手机的高度和宽度如下图

Point p = new Point();
getWindowManager().getDefaultDisplay().getSize(p);
p.x //width 540
p.y //height 960

我写了一个demo,但是得到的值不对 像这样的demo

import android.graphics.Point;

public class Strike {
    private StrikeView view;
    private int left = 0;
    private int top = 0;
    private Point win;
    private boolean isDown = true;
    private boolean isRight = true;

    public Strike(StrikeView view, Point win) {
        this.view = view;
        this.win = win; 
        this.left = view.getLeft();
        this.top = view.getTop();
    }

    /**
     * Set direction and refresh
     */
    public void setPostion() {
        view.setLeft(left);
        view.setTop(top);
        view.invalidate();
    }

    /**
     * calculate view direction
     */
    public void postion() {
        if (isRight) {
            if (left + 30 < win.x)
                left++;
            else {
                isRight = false;
                left--;
            }
        } else {
            if (left > 0)
                left--;
            else {
                isRight = true;
                left++;
            }
        }
        if (isDown) {
            if (top + 30 < win.y)
                top++;
            else {
                isDown = false;
                top--;
            }
        } else {
            if (top > 0)
                top--;
            else {
                isDown = true;
                top++;
            }
        }

    }

}
4

3 回答 3

1

这是我使用的(在 Android 2.1+ 上测试):

private void size() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
        size_old(getWindowManager().getDefaultDisplay());
    }
    else {
        size_new(getWindowManager().getDefaultDisplay());
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void size_new(Display display) {
    Point point = new Point();
    display.getSize(point);
            // point.x and point.y
}

@SuppressWarnings("deprecation")
private String size_old(Display display) {
    // display.getWidth() and display.getHeight()
}
于 2012-11-19T10:00:42.163 回答
0

要知道任何手机的尺寸都值得使用这种方法......

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int wwidth = displaymetrics.widthPixels;
于 2012-11-19T10:27:49.977 回答
0

用这个:

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
于 2012-11-24T10:14:43.670 回答