Skip to content
Advertisement

How can I change the width of an image button in a horizontal scroll view?

I’m trying to create a page that looks like the contribution page of GitHub (like each square represents a day, and the transparency of the square represents the number of commits). I want the page to look something like this:

enter image description here

So, I made a horizontal scroll view because I want the section of squares can be scrolled horizontally. And I tried to add the squares into the HSV. Here’s the code:

<HorizontalScrollView
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="295dp"
    android:layout_marginTop="10dp"
    android:layout_marginRight="60dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/time">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="20dp"  <!-- the problem -->
        android:layout_height="35dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@drawable/square" />

</HorizontalScrollView>

The problem is, I cannot set the layout_width of the image button, no matter what I change it to, the design always remain like this:

enter image description here

As you can see, the height is correct, but the width is fixed at a weird place. Is there anyway I can change it?

Any help would be appreciated.

Advertisement

Answer

You should use the layout inside of the HorizontalScrollView instead of adding the image button directly. For example LinearLayout or GridLayout

The point is that the scroll view can only have one child, because the scroll view extended FrameLayout

Quote from the documentation:

Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. A HorizontalScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects. A child that is often used is a LinearLayout in a horizontal orientation, presenting a horizontal array of top-level items that the user can scroll through.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement