获取视图的实际高度视图、高度、实际

2023-09-05 08:56:48 作者:旧颜。

简单的问题,也许是令人沮丧的,复杂的,但是 - 希望 - 简单的答案?

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

什么是最佳实践为获得具有它的大小设置为FILL_PARENT元素的实际高度是多少?

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

推荐答案

绝对是比它更复杂,似乎是应该的。我发现相比于建议问题的答案更简单的方法,就是用一个ViewTreeObserver。在您的onCreate()方法,你可以使用一些code,如以下内容:

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.
    }
}
 
精彩推荐
图片推荐