[英]Obtain width and height of a Layout
當我嘗試獲取如下所示的參數時,我有一個FrameLayout:
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()來執行此操作,結果相同。 顯然,此布局的高度和寬度不是這些值。
如何有效檢索布局的大小?
返回的值是正確的,因為:
-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());
}
});
在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
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.