如何将多个imageView填充到一行(允许重叠)?

时间:2017-11-08 15:49:04

标签: android android-layout layout

我有一定数量的缩略图,我想布置左对齐,但如果图像不适合屏幕,我希望每个图像与左邻居重叠。

它看起来像封面流或轮播视图,但是静态的。

一行中显示的图像数量从一开始就是已知的,不会改变。另外:不需要3D效果。只是平坦,水平填充,重叠的图像。

我尝试使用负边距的LinearLayout:无法确定设置的边距有多大。

我尝试过PercentageRelativeLayout:无法实现左对齐行为

请告诉我如何以编程方式进行操作。

我想要的草图很简单:
A poor sketch of what i want

我实施了Chris Parkers的建议(尽管我必须以编程方式进行,我使用axml进行测试):

<LinearLayout
  android:id="@+id/loPreviews"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1">
      <ImageView
          android:layout_width="@dimen/filePreviewHeight"
          android:layout_height="@dimen/filePreviewHeight"
          android:src="@drawable/img1"
          android:adjustViewBounds="true" />
  </LinearLayout>
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1">
      <ImageView
          android:layout_width="@dimen/filePreviewHeight"
          android:layout_height="@dimen/filePreviewHeight"
          android:src="@drawable/img2"
          android:adjustViewBounds="true" />
  </LinearLayout>
  <!-- more images-->
</LinearLayout>

此解决方案的问题在于,图像具有不同的纵横比,并且它们以错误的方式裁剪或适合带边框的正方形。没有android:scaleType允许我正确裁剪(保留整个高度并仅切断正确的部分)。

可以通过根据每个图像的宽高比设置每个layout_width的{​​{1}}来解决这个问题。此外,将权重设置为等于图像的宽度,以便更好地分配。最右边的LinearLayout获取宽度wrap_content,以显示完整的图像。

但是如果没有使用所有的水平空间,这个解决方案不会左对齐图像!

1 个答案:

答案 0 :(得分:-1)

您可以使用LinearLayout作为父布局。然后将每个图像包装在自己的LinearLayout中。每个Image容器都应定义一个权重值,并且它们都应具有相同的值,以便父布局中的空间平均分配为每个图像容器的相同数量。您的图像需要声明宽度和高度,以防止ImageView调整图像大小以适应容器布局。这是一个非常难看的解决方案,但我认为它可行。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp">

    <!-- Repeat this for every image -->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:adjustViewBounds="true"
            android:src="@drawable/image1"/>

    </LinearLayout>

    <!-- Repeat this for every image -->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:adjustViewBounds="true"
            android:src="@drawable/image2"/>

    </LinearLayout>

    <!-- ... -->
</LinearLayout>