2015-02-23 153 views
0

我有一個FrameLayout裏的,當我試圖得到它的PARAMS這樣的:獲取寬度和高度的佈局

ViewGroup.LayoutParams params = cameraPreviewFrameLayout.getLayoutParams(); 
int layoutHeight = params.height; 
int layoutWidth = params.width; 

這裏,layoutHeight是-2,layoutWidth爲-1。這是我的XML:

<FrameLayout 
    android:id="@+id/liveActivity_cameraPreviewFrameLayout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true"/> 

我執行從的onCreate這個動作,而且我通過在onStart()試圖給它,同樣的結果。顯然這個佈局的高度和寬度不是這些值。

如何有效檢索佈局的大小?

回答

1

返回的值是正確的,因爲:

-2 stands for LayoutParams.WRAP_CONENT 
-1 stands for LayoutParams.MATCH_PARENT 

如果你想獲得精確值,你需要使用的方法的getHeight和的getWidth。然而這些方法只能使用一次的佈局已經測得,所以耽誤您的通話是這樣的:

cameraPreviewFrameLayout.post(new Runnable() { 
    @Override 
    public void run() { 
     View v = cameraPreviewFrameLayout; 
     Log.e("TAG", v.getWidth() + ":" + v.getHeight()); 
    } 
}); 
1

有道後或內onLayoutChange方法調用越來越佈局的大小

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final FrameLayout layout = (FrameLayout) findViewById(R.id.liveActivity_cameraPreviewFrameLayout); 
    layout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { 
     @Override 
     public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
      int width = right - left; 
      int height = bottom - top; 
      Log.v("TAG", String.format("%d - %d", width, height)); 
      //Or 
      Log.v("TAG", String.format("%d - %d", layout.getWidth(), layout.getHeight())); 
      //And after this method call, calling layout.getWidth() and layout.getHeight() will give right values 
     } 
    }); 
} 
+0

這種運作良好。 – svprdga 2015-02-24 10:17:50