【发布时间】:2013-07-08 09:29:21
【问题描述】:
我在相对布局中有一个 ImageView 和 3 个 TextView,并且需要在运行时根据图像的大小定位文本视图。目前我在图像上使用 ViewTreeObserver,以便我可以使用它的宽度/高度来定位文本框。
一切正常,除了 TextViews 在加载时跳转到正确的位置,使它看起来像有闪烁。
有没有办法在屏幕呈现之前重新定位 TextView,但一旦 ImageView 设置了它的宽度和高度?
这是 XML 代码的(简化)版本:
<RelativeLayout
android:id="@+id/relativeLayoutMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/myImage"
android:src="@drawable/myImageSrc"
android:adjustViewBounds="true"
android:scaleType="fitStart"
android:layout_alignParentStart="true"/>
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..."
android:layout_alignLeft="@+id/myImage"
android:layout_alignTop="@+id/myImage"/>
</RelativeLayout>
这是我在 addOnGlobalLayoutListener 回调中使用的代码,用于在运行时定位文本视图:
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayoutMain);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
int width = relativeLayout.getMeasuredWidth();
int height = relativeLayout.getMeasuredHeight();
TextView tv = (TextView) findViewById(R.id.myTextView);
int w = tv.getMeasuredWidth();
int h = tv.getMeasuredHeight();
layoutParams.setMargins((int) (width * 0.5 - w / 2), (int) (height * 0.54 - h / 2), 0, 0);
tv.setLayoutParams(layoutParams);
【问题讨论】:
-
是的,有!在xml布局中。您可以在 xml 中轻松完成此操作。只需发布您的布局 xml 代码,以便我提供帮助。
-
我怀疑您只是希望您的
TextViews 可能始终低于或高于ImageView。如果是这种情况,那么它可以在 xml 中完成,但如果有类似放置TextView将 A 放置为 x 大小但对于大小为 y 放置 B 完全不同的东西,那么它需要在运行时完成。 -
应该是后者。该位置取决于仅在运行时知道的 ImageView 的大小。我确实考虑过隐藏 TextView 直到它们处于正确的位置 - 这至少意味着它们不会跳转位置。
-
相信我,只要你不跳来跳去寻找不同的尺寸,这并不重要。只需发布您的 xml 并准确告诉我您想要什么。您希望您的
TextView位于ImageView的左侧、右侧、底部或顶部,只要此约束不改变您不需要在运行时执行此操作。您可以在运行时加载任何大小,并且 UI 不会中断。但是如果你还是坚持做的话可以考虑使用nineoldandorid动画框架。 -
上面添加了额外的细节。如果它只能在 XML 中实现,那么我宁愿那样做!
标签: android rendering android-relativelayout