Создание прокрутки

Последнее обновление: 29.03.2024

Вполне может оказаться, содержимое какого-либо компонента больше размера контейнера. В этом случае очевидным решением будет создание прокрутки. Однако по умолчанию она отстутсвует, ее необходимо добавлять вручную. Рассмотрим, как это сделать

Прокрутка по горизонтали

Для добавления прокрутки содержимого по горизонтали применяется модификатор Modifier.horizontalScroll:

fun Modifier.horizontalScroll(
    state: ScrollState,
    enabled: Boolean = true,
    flingBehavior: FlingBehavior? = null,
    reverseScrolling: Boolean = false
): Modifier

Параметры модификатора:

  • state: представляет объект ScrollState и описывает состояние полосы прокрутки

  • enabled: значение типа Boolean, которое указывает, будет ли прокрутка доступна. По умолчанию имеет значение true

  • flingBehavior: представляет объект FlingBehavior и описывает поведение при завершении прокрутки. По умолчанию имеет значение ScrollableDefaults.flingBehavior

  • reverseScrolling: устанавливает направление. При значении true прокрутка идет в обратном направлении. По умолчанию имеет значение false

Применим горизонтальную прокрутку к компоненту Text:

package com.example.helloapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{
            Text(
                "What is Lorem Ipsum?\n" +
					"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
                    "\n" +
                   "...............",
                fontSize=22.sp,
                modifier = Modifier.horizontalScroll(ScrollState(0))
            )
        }
    }
}

Здесь в модификатор .horizontalScroll(ScrollState(0)) передается объект ScrollState, которые инициализирован числом 0 - это начальное положение полосы прокрутки, а именно 0 пикселей. Соответственно, если мы хотим, чтобы скролл устанавливался на каком-то другом положении, то можно передать другое значение.

Создание прокрутки в Jetpack Compose на Android

Тип rememberScrollState

Хотя мы можем сами определять состояние полосы покрутки с помощью объекта ScrollState, но Jetpack Compose также предлагает встроенную реализацию в виде типа rememberScrollState:

package com.example.helloapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{
            Text(
                "What is Lorem Ipsum?\n" +
					"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
                    "\n" +
                   "...............",
                fontSize=22.sp,
                modifier = Modifier.horizontalScroll(rememberScrollState())
            )
        }
    }
}

Прокрутка по вертикали

Для добавления прокрутки содержимого по вертикали применяется модификатор Modifier.verticalScroll:

fun Modifier.verticalScroll(
    state: ScrollState,
    enabled: Boolean = true,
    flingBehavior: FlingBehavior? = null,
    reverseScrolling: Boolean = false
): Modifier

Данный модификатор принимает те же значения и работает в приниципе также, как и horizontalScroll, только по вертикали. Применим данный модификатор:

package com.example.helloapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{
            Text(
                "What is Lorem Ipsum?\n" +
					"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
                    "\n" +
                   "...............",
                fontSize=22.sp,
                modifier = Modifier.verticalScroll(rememberScrollState())
            )
        }
    }
}

Сочетание прокруток по горизонтали и вертикали

Применяя оба модификатора - horizontalScroll() и verticalScroll(), можно совместить прокрутку по горизонтали и вертикали:

Text(
	"What is Lorem Ipsum?\n" +
		"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
        "\n" +
        "...............",
    fontSize=22.sp,
	modifier = Modifier
                .verticalScroll(rememberScrollState())
                .horizontalScroll(rememberScrollState())
)
Помощь сайту
Юмани:
410011174743222
Перевод на карту
Номер карты:
4048415020898850