Why does calling getWidth() on a View in onResume() return 0?

后端 未结 2 814
感情败类
感情败类 2020-11-30 11:40

Everything I\'ve read says you can\'t call getWidth() or getHeight() on a View in a constructor, but I\'m calling them in onResu

2条回答
  •  旧巷少年郎
    2020-11-30 12:08

    you have to wait that the the current view's hierarchy is at least measured before getWidth and getHeigth return something != 0. What you could do is to retrieve the "root" layout and post a runnable. Inside the runnable you should be able to retrieve width and height successfully

    root.post(new Runnable() {
         public void run() {
             LinearLayout test = (LinearLayout) findViewById(R.id.myview);
             double widthpx = test.getWidth();
         }
    });
    

提交回复
热议问题