我有一个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()来获得相同的结果。显然,这种布局的高度和宽度不是这些值。
如何有效地检索布局的大小?
答案 0 :(得分: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 :(得分: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
}
});
}