Android get layout height and width in a fragment

后端 未结 3 627
时光取名叫无心
时光取名叫无心 2020-12-15 05:40

I am working on a fragment and I want to get the dimension of a layout contained in the xml fragment layout. When I try the code

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 06:37

    There's a cleaner solution to this, just use the View.post() method on your fragment's root view, and you can call getMeasuredHeight()/getMeasuredWidth() and get the actual values.

    E.g.

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.myfragment, container, false);
    
        root.post(new Runnable() {
            @Override
            public void run() {
                // for instance
                int height = root.getMeasuredHeight(); 
            }
        });
    
        return root;
    }
    

    Very neat and tidy and no messy mucking about with the ViewTreeObserver.

    I've only tested this with android-23 devices, but the API has had this method since level 1.

    Anyway, WFM.

提交回复
热议问题