在Android 2.2上获取屏幕宽度和高度

时间:2014-11-10 08:54:38

标签: android

如何在Android版本2.2(API lv8)的设备上获取屏幕宽度和高度以使用此值。 我使用这段代码:

public static Point Maximum(Context context)
       {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();  // deprecated
            int height = display.getHeight();  // deprecated
            Point temp=new Point();     
            return temp;
       }

当我想通过打印Max点检查textview:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView txt= (TextView)findViewById(R.id.text1);
    txt.setText(Math.Maximum(this).toString()); 
}

点是(0,0)。什么问题?

4 个答案:

答案 0 :(得分:1)

试试这段代码。但是,在您可以使用此SDK的新SDK版本中不推荐使用此API。

Display display = activity.getWindowManager().getDefaultDisplay();
int width  = display.getWidth();
int height = display.getHeight();

答案 1 :(得分:0)

试试这段代码:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

答案 2 :(得分:0)

尝试这样可以获得屏幕宽度。类似地,您可以获得屏幕高度,也可以自定义相同的内容,以便在单个函数中返回它们。

 @SuppressWarnings("deprecation")
 @SuppressLint("NewApi")
 private int getScreenWidth() {
    int width = 400;
    int height = 600; // just intialising it to default value in case if there is any problem getting screen width
    WindowManager wm = (WindowManager) activity // activity is the context if you are using this method in adapter. Otherwise in Activity you can simply ignore this
            .getSystemService(Context.WINDOW_SERVICE); 
    Display display = wm.getDefaultDisplay();
    if (android.os.Build.VERSION.SDK_INT >= 13) {
        Point size = new Point();
        display.getSize(size);
        width = size.x;
        height = size.y;
    } else {
        width = display.getWidth();
        height= display.getHeight();
    }
    return width;//or height
}

答案 3 :(得分:0)

获取设备宽度和高度,返回点。希望你喜欢这个。

public static Point Maximum(){
    Display display = activity.getWindowManager().getDefaultDisplay();
    int width  = display.getWidth();
    int height = display.getHeight();
    Point temp=new Point();
    temp.set(width, height);     
    return temp;
}