How to get USABLE screen width and height in Android

微笑、不失礼 提交于 2019-12-05 10:21:35

I had the same question a while back and here is the answer that i found. Shows the activity dimensions.

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.graphics.Point;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main)

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        int width = size.x;
        int height = size.y;

        //Set two textViews to display the width and height
        //ex: txtWidth.setText("X: " + width);
    }
}

I know this question is really old, but I have fought with this so many times until I found this stupidly simple solution:

public final void updateUsableScreenSize() {
    final View vContent = findViewById(android.R.id.content);
    vContent.post(new Runnable() {
        @Override
        public void run() {
            nMaxScreenWidth = vContent.getWidth();
            nMaxScreenHeight = vContent.getHeight();
        }
    });
}

Run this code after setContentView() in your Activity's onCreate(), and delay any code that depends on those values until onCreate() is finished, for example by using post() again after this one.

Explanation: This code obtains your activity's root view, which can always be accessed by generic resource id android.R.id.content, and asks the UI handler to run that code as the next message after initial layout is done. Your root view will be of the exact size you have available. You cannot run this directly on the onCreate() callback because layout did not happen yet.

you can use also the full screen

developer.android

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