Android: get width of Layout programatically having fill_parent in its xml

前端 未结 5 1772
误落风尘
误落风尘 2021-02-08 07:03

I have the a LinearLayout with width set in xml as fill_parent , now i need its width at runtime programatically. So i did this:

    Li         


        
5条回答
  •  北海茫月
    2021-02-08 07:27

    If you look at the value for FILL_PARENT (you should be using MATCH_PARENT since FILL_PARENT is now deprecated) you will notice the value for it is -1. LayoutParams are simply attributes for how your view should look. Once the view is inflated and looks the way the params specify, the view does not go back and change those Params to reflect the actual values of the view (width/height/etc).

    If you wanted to get the actual width of your view you would have to call getWidth() on your view once the layout has been inflated and displayed. Calling getWidth() before your layout has been displayed will result in 0.

    LinearLayout layoutGet=(LinearLayout) findViewById(R.id.GameField1);
    int width = layoutGet.getWidth();
    

提交回复
热议问题