【问题标题】:Layout with center of view matches center of central item with minimum padding具有视图中心的布局与具有最小填充的中心项目的中心相匹配
【发布时间】:2011-11-17 20:43:26
【问题描述】:

我正在尝试使用图像和两个标签(一个在图像上方,一个在图像下方)创建简单的布局。我使用膨胀视图将其绘制到画布上。我的兴趣是使用以图像中心为中心的矩形创建视图。不希望使用 fill_parent 或 match_parent 尺寸进行布局,因为最终视图将占用所有可用空间,而不是最小空间(导致位图太大)。

这是我目前使用的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView android:layout_centerInParent="true"
        android:layout_width="wrap_content" android:id="@+id/ivBeaconType"
        android:layout_height="wrap_content" android:src="@drawable/bt_beacon"></ImageView>
    <TextView android:layout_above="@id/ivBeaconType" android:layout_centerHorizontal="true"
         android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="12dp" android:text="AABBCCDDEEFF" android:id="@+id/tvId"
        android:textColor="#72C8E0"></TextView>
    <TextView android:layout_below="@id/ivBeaconType" android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="-99 dB" android:id="@+id/tvRssi" android:textColor="#FF0000"></TextView>
</RelativeLayout>

这有问题。相对布局不会增长到适合两种文本(上面的标签没有显示,底部的标签画得太靠近图像)。我可以通过在第一个文本下方对齐图像和在图像下方对齐第三个文本来正确渲染视图,但这不会导致图像中心周围的完美中心(或使用线性布局)。

能做什么?另一个有效的解决方案是获取图像相对于布局绘图区域的中心。有什么想法吗?

【问题讨论】:

  • 一张描述你想要达到的目标的图片会很棒

标签: android image layout


【解决方案1】:

我明白了。视图的 getLeft()/getRight()/getTop()/getBottom() 方法返回父级中的相对位置。唯一的验证码是它们只在布局阶段之后返回有效值,所以这解决了我的问题:

    if (beaconBitmap == null)
    {
        /* Calculamos las dimensiones si no está creado el bitmap */
        beaconView.invalidate();
        beaconView.refreshDrawableState();
        beaconView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        beaconView.layout(0, 0, beaconView.getMeasuredWidth(),
                beaconView.getMeasuredHeight());
        ImageView ivBeaconType = (ImageView) beaconView
                .findViewById(R.id.ivBeaconType);
        Rect beaconIconArea = new Rect(ivBeaconType.getLeft(),
                ivBeaconType.getTop(), ivBeaconType.getRight(),
                ivBeaconType.getBottom());
        beaconBitmapCenterX = beaconIconArea.centerX();
        beaconBitmapCenterY = beaconIconArea.centerY();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多