How to get USABLE screen width and height in Android

女生的网名这么多〃 提交于 2019-12-10 05:35:10

问题


I'm creating an app where I really need to know the correct screen dimensions. Actually I know how to do that... but a problem appeared, because even if you dorequestWindowFeature(Window.FEATURE_NO_TITLE);, this:

still stays on the screen and it seems, it's also counted as a part of the screen so the "screenWidth" is actually bigger, than the usable part.

Isn't there any method how to get the size of the usable part and not whole screen? Or at least get the sizes of the 'scrolling thing'(but there would be a problem, that there are devices that don't show them)?


回答1:


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



回答2:


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.




回答3:


you can use also the full screen

developer.android



来源:https://stackoverflow.com/questions/24017774/how-to-get-usable-screen-width-and-height-in-android

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