【问题标题】:Use maxHeight and weight at the same time同时使用 maxHeight 和 weight
【发布时间】:2016-03-07 11:03:35
【问题描述】:

我有一个父 LinearLayout,里面有一个 ImageView 和一个孩子 LinearLayoutLinearLayout 子元素里面有可以有不同长度的文本。我希望 ImageView 始终具有相同的大小 (200dpx200dp) 并且仅在子 LinearLayout 的文本溢出时按比例缩小

为此,我在 ImageView 子项中使用了 layout_weightmaxHeight,但由于 layout_weight,maxHeight 不起作用。当子 LinearLayout 的文本没有溢出时,ImageView 不是平方的,而是显示为矩形。

我该怎么做?

这是代码

<ImageView
        android:id="@+id/charImage"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:maxWidth="200dp"
        android:maxHeight="200dp"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:src="@drawable/jon_snow" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="vertical">
        ----some childs----
   </LinearLayout>

这就是它应该的样子,一个 square ImageView,下面有一些文本,与文本的长度无关。

编辑

我尝试修改自定义 ImageView 的 onMeasure(),但它没有正确调整大小并且占用了 LinearLayout 子项的一些空间并且文本溢出

  @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = Math.min(widthMeasureSpec, Math.min(heightMeasureSpec, dpToPx(200)));
    setMeasuredDimension(height, height);

}

private int dpToPx(int dp){

    float density = getResources().getDisplayMetrics().density;
    return Math.round((float)dp * density);
}

【问题讨论】:

    标签: android android-layout android-studio android-layout-weight


    【解决方案1】:

    并不能保证图像会因为其最大宽度和高度是平方的而被平方。这意味着如果它在两个方向上都填充了它的最大尺寸,它将是方形的。如果要确保其平方,子类 ImageView 并覆盖 onMeasure 以强制它为平方尺寸。

    我也不知道 weight 是否适用于 maxXXX。但更糟糕的情况是,您可以通过强制它不大于 200 来使其在 onMeasure 中发挥作用。

    【讨论】:

    • 我试图重写 onMeasure 方法,并且 ImageView 显示为平方,但如果我这样做,如果 LinearLayout 的文本溢出,它不会重新调整大小。我用这个答案stackoverflow.com/questions/16506275/…
    • 您需要 onMeasure 工作来确保正方形。但是你想做一些不同的事情。将宽度和高度都设置为 Math.min(widthMeasureSpec, Math.min(heightMeasureSpec, 200dp))。基本上是允许的宽度、高度或 200dp,以最小者为准。
    • 请注意,度量规格的数量以像素为单位,因此您需要将 200dp 转换为像素,而不是使用 200 作为常数。
    • 嗨 Gabe 我之前无法测试它我已经用你的解决方案编辑了帖子,也许我做错了什么,但它不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2012-04-20
    • 2022-12-21
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多