Search code examples
androidbuttontextviewscrollviewhorizontalscrollview

TextView pushes buttons off screen with HorizontalScrollView


I am aiming for a layout similar to the native calculator app. I want text to trail off the left of the screen without moving the buttons on the right. Currently my text moves to the left until filling the screen at which point the buttons are pushed off the right edge.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_weight="1"
    android:gravity="right"
    android:orientation="horizontal" >

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="none" >

        <TextView
            android:id="@+id/display_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@android:color/white"
            android:textIsSelectable="true"
            android:textSize="30sp" />
    </HorizontalScrollView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/delete_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onDelete"
            android:text="@string/delete_button" />

        <Button
            android:id="@+id/equate_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onEquate"
            android:text="@string/equate_button" />
    </LinearLayout>
</LinearLayout>

Solution

  • You don't need to put your TextView into a HorizontalScrollView, it will automatically become scrollable when the text exceeds the bounds. See docs: http://developer.android.com/reference/android/widget/TextView.html#attr_android:scrollHorizontally

    Just add android:scrollHorizontally="true" to the TextView in the layout.

    You may also need to change the text view's layout_weight to 0 or set its layout_width to something fixed (like 100dp).

    To get the text to go right-to-left, set the gravity on the TextView to be android:gravity="right|center_vertical"

    I also humbly refer you the source of the calculator app you are trying to emulate: https://github.com/android/platform_packages_apps_calculator/tree/master/src