获得实际的视图高度

Won*_*ane 4 size android android-layout

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

获取其大小设置为FILL_PARENT的元素的实际高度的"最佳实践"是什么?

kco*_*ock 17

绝对比看起来应该更复杂.与建议问题中的答案相比,我发现的一种更简单的方法是使用ViewTreeObserver.在onCreate()方法中,您可以使用以下代码:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)