content view width and height

后端 未结 3 727
野的像风
野的像风 2020-12-21 07:14

I am using below steps to know the width and height of contentview on my display screen

ContentViewWidth = getWindow().findViewById(Window.ID_ANDROID_CONTENT         


        
3条回答
  •  没有蜡笔的小新
    2020-12-21 07:35

    Here's what I did in my activity to figure out the content layout of a particular view child that I knew stretched end-to-end on the screen (a webview in this case):

    First, inherit from OnGlobalLayoutListener:

    public class ContainerActivity extends Activity implements ViewTreeObserver.OnGlobalLayoutListener {
    ...
    

    Next, implement onGlobalLayout method of listener's interface (note I do some pixel calcs that pertain to figuring out the medium-zoom dip :

    @Override
    public void onGlobalLayout() {
        int nH = this.mWebView.getHeight();
        int nW = this.mWebView.getWidth();
    
        if (nH > 0 && nW > 0)
        {
            DisplayMetrics oMetrics = new DisplayMetrics();
    
            this.getWindowManager().getDefaultDisplay().getMetrics(oMetrics); 
    
            nH = (nH * DisplayMetrics.DENSITY_DEFAULT) / oMetrics.densityDpi;
            nW = (nW * DisplayMetrics.DENSITY_DEFAULT) / oMetrics.densityDpi;
    
            // do something with nH and nW                  
    
            this.mWebView.getViewTreeObserver().removeGlobalOnLayoutListener
                ( this
                );
    
                ...         
        }
    }
    

    Finally, make sure to tell the view element (mWebView in this case) inside onCreate() that you're listening to layout events:

    this.setContentView(this.mWebView = new WebView(this));
    
    this.mWebView.getViewTreeObserver().addOnGlobalLayoutListener
        ( this
        );
    

    This approach works for older android versions. I believe ics+ has a layout listener for each view you can bind to, and as such, would be used in a similar way.

提交回复
热议问题