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

前端 未结 5 1776
误落风尘
误落风尘 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:18

    You can try to listen to the globalLayout event, and get the width in there. You probably get the -1 because you are trying to get the width before the views are layed-out.

    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
           //Do it here
           LinearLayout layoutGet=(LinearLayout) findViewById(R.id.GameField1);
           LayoutParams layParamsGet= layoutGet.getLayoutParams();
           int width=layParamsGet.width;
           removeOnGlobalLayoutListener(layoutGet, this); // Assuming layoutGet is the View which you got the ViewTreeObserver from
        }
    });
    
    @SuppressLint("NewApi")
    public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
        if (Build.VERSION.SDK_INT < 16) v.getViewTreeObserver().removeGlobalOnLayoutListener(listener); 
        else v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    }
    

    (vto is the view you want to get the width of)

提交回复
热议问题