Why does LinearLayout child getWidth method return 0?

前端 未结 3 1583
死守一世寂寞
死守一世寂寞 2020-12-07 04:08

I have a LinearLayout, and this LinearLayout will hold dynamically placed views. I need to find out what the width of the children of LinearLayout, however this has to be do

相关标签:
3条回答
  • 2020-12-07 04:54

    You might be able to get with the below. But as others pointed out, this probably isn't a great idea.

    LinearLayout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    LinearLayout.getMeasuredWidth();
    
    0 讨论(0)
  • 2020-12-07 05:07

    inside the onCreate , views still can't know the state of the nearby views and the children ,etc... so only after all is prepared and the layout process is done , you can get the size of views .

    here's a quick code for getting the size of the view just before it's being drawn:

    private static void runJustBeforeBeingDrawn(final View view, final Runnable runnable)
    {
        final ViewTreeObserver vto = view.getViewTreeObserver();
        final OnPreDrawListener preDrawListener = new OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                Log.d(App.APPLICATION_TAG, CLASS_TAG + "onpredraw");
                runnable.run();
                final ViewTreeObserver vto = view.getViewTreeObserver();
                vto.removeOnPreDrawListener(this);
                return true;
            }
        };
        vto.addOnPreDrawListener(preDrawListener);
    }
    

    alternatively , you can use addOnGlobalLayoutListener instead of addOnPreDrawListener if you wish.

    example of usage :

    runJustBeforeBeingDrawn(view,new Runnable()
    {
      @Override
      public void run()
      {
        int width=view.getWidth();
        int height=view.getHeight();
      }
    });
    

    another approach is to use onWindowFocusChanged (and check that hasFocus==true) , but that's not always the best way ( only use for simple views-creation, not for dynamic creations)

    EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126

    0 讨论(0)
  • 2020-12-07 05:10

    https://stackoverflow.com/a/3594216/1397218

    So you should somehow change your logic.

    0 讨论(0)
提交回复
热议问题