Get Actual Height of View

走远了吗. 提交于 2019-11-29 22:07:29

问题


Simple question, perhaps frustratingly-complex-but-hopefully-simple answer?

What is the "Best Practice" for getting the actual height of an element that has its size set to FILL_PARENT?


回答1:


Definitely is more complicated than it seems it should be. An easier way that I've found compared to the answer in the suggested question, is to use a ViewTreeObserver. In your onCreate() method, you can use some code such as the following:

TextView textView = (TextView)findViewById(R.id.my_textview);
ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //in here, place the code that requires you to know the dimensions.
        //this will be called as the layout is finished, prior to displaying.
    }
}



回答2:


Just an extra amendment to the above answer, if you need to perform any operations to dimensions of multiple components in a view. The layout listener is called for each view as its layout completes. This is recursively true up to the root view component (i.e. child elements generate layout events, then the parent element generates its layout event). What this means is that you can simply hook onto the root view component's layout event to be notified when any view's layout changes.

ViewTreeObserver observer = this.findViewById(android.R.id.content).getViewTreeObserver();

Now you can expect that all your views will have width and height values set in onGlobalLayout because they've all performed their layout. This is obviously preferable to creating many listeners for each view that needs to expose its actual dimensions (unless of course you absolutely must have scope for which view generated the event, which is typically not necessary).



来源:https://stackoverflow.com/questions/4501840/get-actual-height-of-view

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