getWidth和getHeight有时会返回0,有时不会返回4.4.2

时间:2014-04-09 17:29:48

标签: android android-layout android-4.4-kitkat

我有一个RelativeLayout指定如下

<RelativeLayout
    android:id="@+id/buttons_layout"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:paddingTop="80dip" >
</RelativeLayout>

在MainActivity上我这样做

mButtonsLayout = (RelativeLayout) findViewById(R.id.buttons_layout);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
mButtonsLayout.addView(new PathMenu(this, entries, this, fullDataPackage.getSnapshot().getUnlistenedCalls()), lp);

PathMenu是RelativeLayout的扩展,实质上是一个动画图形菜单。图标从屏幕侧面滑入,并围绕中心图形旋转到它们的位置。

中心图形添加到代码

mMenuButton = new ImageButton(getContext());
mMenuButton.setBackgroundResource(R.drawable.selector_refresh_button);
mMenuButton.setOnClickListener(menuButtonClickListener);
addView(mMenuButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

以后它被移到中心

LayoutParams params = (LayoutParams) mMenuButton.getLayoutParams();
params.topMargin = (getHeight() - mMenuButton.getHeight()) / 2;
params.leftMargin = (getWidth() - mMenuButton.getWidth()) / 2;
mMenuButton.setLayoutParams(params);

这适用于4.3及以下版本。 4.4在大约50%的时间里工作。一半时间getHeight()和getWidth()返回0,另一半时间返回正确的值。这两个函数,除非我弄错了,都在我的PathMenu对象上执行,该对象的高度和宽度为MATCH_PARENT,它的父级是我发布的第一个布局,其宽度为fill_parent,高度为0dip。我用4.4.2的目标编译我的代码,它在4.3或以下设备上运行良好,但在4.4.2设备上搞乱(当我用4.3或4.2的目标编译时,它做同样的事情然后在设备上运行,4.3和工作,而4.4.2混乱)。

为什么它会破坏4.4+设备以及如何解决?

1 个答案:

答案 0 :(得分:1)

这是我提出的解决方案。如果有人有不同或更好,请发布。

由于问题仅出现在4.4.2(以及未来,我假设)中,我使用了if和SDK_INT为19和更高版本做了不同的事情。问题似乎是图片在显示之前没有高度和宽度,而在4.4.2有时在显示后的短时间内,getWidth()getHeight()功能仍会返回0.但是,假设我没有对图像进行缩放,我可以使用getBackground().getIntrinsicHeight()getBackground().getIntrinsicWidth()并使用它。为了获得屏幕宽度和高度,我在显示器上使用getSize(point),因为我使用屏幕尺寸而不是相对视图的大小我需要获取父级的填充以便居中它正确。

LayoutParams params = (LayoutParams) mMenuButton.getLayoutParams();
if (android.os.Build.VERSION.SDK_INT >= 19) {
  RelativeLayout mButtonsLayout = (RelativeLayout) getParent();
  WindowManager wm = (WindowManager) mcontext.getSystemService(Context.WINDOW_SERVICE);
  Display display = wm.getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  params.topMargin = (size.y - mMenuButton.getBackground().getIntrinsicHeight()) / 2 - mButtonsLayout.getPaddingTop();
  params.leftMargin = (size.x - mMenuButton.getBackground().getIntrinsicWidth()) / 2;
}
else {
  params.topMargin = (getHeight() - mMenuButton.getHeight()) / 2;
  params.leftMargin = (getWidth() - mMenuButton.getWidth()) / 2;
}
mMenuButton.setLayoutParams(params);

可能有一个更好的解决方案,我希望有人发布,但此解决方案目前正在为我工​​作。