Android:获取布局的宽度,以编程方式在其xml中使用fill_parent

Naj*_*hah 9 android android-intent android-layout

我有一个LinearLayout宽度设置为xml 的a fill_parent,现在我在运行时以编程方式需要它的宽度.所以我这样做了:

    LinearLayout layoutGet=(LinearLayout) findViewById(R.id.GameField1);
    LayoutParams layParamsGet= layoutGet.getLayoutParams();
    int width=layParamsGet.width;
Run Code Online (Sandbox Code Playgroud)

但是width发现调试的价值是-1,任何有想法的人为什么不能在运行时获得LinearLayout的确切宽度,并在layout xml中设置fill_parent.

Ton*_*ony 36

Jens Vossnack的方法很好.但是,我发现GlobalLayoutListener的onGlobalLayout()方法被重复调用,在某些情况下可能不合适.

我有一个更简单的方法.

myLayout = (RelativeLayout) findViewById(R.id.my_layout);
myLayout.post(new Runnable() 
    {

        @Override
        public void run()
        {
            Log.i("TEST", "Layout width : "+ myLayout.getWidth());

        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 为什么它在一个线程中运行良好但在返回0之外呢? (2认同)

小智 5

您可以尝试侦听 globalLayout 事件,并在其中获取宽度。您可能会得到 -1,因为您试图在布局视图之前获得宽度。

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);
}
Run Code Online (Sandbox Code Playgroud)

(vto 是您想要获得宽度的视图)