- ScrollView и HorizontalScrollView
- Методы scrollBy() и scrollTo()
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- 3. Download Drawable Resources Needed
- 2. Modify Values Folder
- 3. Modify Layout Folder
- 4. Create Android ScrollView programmatically in Kotlin
- Set Id of ScrollView
- Set Width and Height of ScrollView
- Set Padding of ScrollView
- Set Margin of ScrollView
- Set Background of ScrollView
- Set Visibility of ScrollView
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- Using ScrollView in Kotlin
- Different Attributes of ScrollView in XML
- Set Id of ScrollView
- Set Width of ScrollView
- Set Height of ScrollView
- Set Padding of ScrollView
- Set Margin of ScrollView
- Set Background of ScrollView
- Set Visibility of ScrollView
- Different Attributes of Android ScrollView Widget
ScrollView и HorizontalScrollView
При большом количестве информации, которую нужно поместить на экране приходится использовать полосы прокрутки. В Android существуют специальные компоненты ScrollView и HorizontalScrollView, которые являются контейнерными элементами и наследуются от ViewGroup. Обратите внимание, что класс TextView использует свою собственную прокрутку и не нуждается в добавлении отдельных полос прокрутки. Но использование отдельных полос даже с TextView может улучшить вид вашего приложения и повышает удобство работы для пользователя.
На панели инструментов компоненты можно найти в разделе Containers.
В контейнеры ScrollView и HorizontalScrollView можно размещать только один дочерний элемент (обычно LinearLayout), который в свою очередь может быть контейнером для других элементов. Виджет ScrollView, несмотря на свое название, поддерживает только вертикальную прокрутку, поэтому для создания вертикальной и горизонтальной прокрутки необходимо использовать ScrollView в сочетании с HorizontalScrollView. Обычно ScrollView используют в качестве корневого элемента, а HorizontalScrollView в качестве дочернего. Можно и наоборот, пробуйте.
В в теле метода onCreate() создайте ссылку на элемент TextView, объявленный в XML-разметке, и запишите в него через метод setText() какой-нибуль длинный текст, который не поместится в видимые размеры экрана устройства:
Запустив проект, вы должны увидеть вертикальную и горизонтальную полосы прокрутки при попытке скролирования.
Если полосы прокрутки вас раздражают, то используйте атрибут android:scrollbars=»none», который скроет их.
По такому же принципу можете вложить ImageView, чтобы просматривать большие картинки:
Методы scrollBy() и scrollTo()
Вы можете программно прокручивать контент с помощью методов scrollBy() и scrollTo(). Например, можно организовать автоматическую прокрутку во время чтения. В нашем примере мы будем прокручивать контент с помощью трёх кнопок.
Сам код для методов:
Дополнительное чтение
Библиотека ParallaxScrollView с использованием эффекта параллакса. Вы прокручиваете длинный текст, а задний фон прокручивается чуть медленнее. Возможно, кому-то пригодится. Там же можно скачать готовое демо и просмотреть в действии.
Источник
Tutorialwing
In this article, we will learn how to create android ScrollView programmatically in Kotlin. We will go through various steps that explains how to create ScrollView and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in ScrollView programmatically, how to set id of ScrollView, how to capitalise text of ScrollView dynamically etc. We will get answer to all such questions in this post.
Output
Tutorialwing Kotlin Dynamic ScrollView Output
Tutorialwing Kotlin Dynamic ScrollView Output
Getting Started
We can define android ScrollView widget as below –
ScrollView is a widget that are used to define vertically scrollable views. It can have only one direct child. So, if you need multiple child views, create a viewGroup as direct child of scrollView. Then, define all the views inside this viewGroup.
Now, how do we use ScrollView in android application ?
Creating New Project
Follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as DynamicScrollView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access ScrollView in Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access view in Kotlin file without using findViewById() method.
Since we have a new project, we will modify the xml and class file to use ScrollView programmatically in kotlin. Please follow the steps below.
3. Download Drawable Resources Needed
You will need some images, stored in res/drawable folder, that will be used in the application. These drawable images will be used by child views of scrollView to create different views.
2. Modify Values Folder
Open res/values/strings.xml file. Add below code into it.
Other values folders have not been changed. So, we are not going to mention it here.
3. Modify Layout Folder
Open res/layout/activity_main.xml file. Add below code into it.
Note that LinearLayout has id rootContainer. In Kotlin file, we will create ScrollView Dynamically and add it into this LinearLayout having id rootContainer.
4. Create Android ScrollView programmatically in Kotlin
Open src/main/java/com.tutorialwing.dynamicscrollview/MainActivity.kt file. Then, add below code into it.
We have defined scrollView programmatically in kotlin file (i.e. in MainActivity.kt file). Then, we have set layout params etc. in it. After that, we have created a linearLayout and added it as direct child of scrollView. Then, we have created 6 imageViews as added it as direct child of linearLayout. Then, we have added scrollView into linearLayout, having id rootContainer.
Finally, when you run the application, you will get output as shown above.
Tutorialwing Kotlin Dynamic ScrollView Output
Tutorialwing Kotlin Dynamic ScrollView Output
Now, Let’s check how to use different attributes of ScrollView to customize it dynamically –
Set Id of ScrollView
Follow steps below to set id of ScrollView programmatically –
- Create ids.xml file in res/values folder. Then, add below code into it –
- Now, we can set id of ScrollView dynamically, in MainActivity.kt file, as –
Here, we have set id of ScrollView using property access syntax – scrollView.id
Set Width and Height of ScrollView
We use layoutParams to set width and height of any View programmatically. In this article, we have added ScrollView in LinearLayout. So, we will define LayoutParams as below –
Here, we have set width and height as WRAP_CONTENT. Some of possible values for width and height are –
- WRAP_CONTENT: Sets value of width or height depending on text inside it.
- MATCH_PARENT: Sets value of width of height depending on width or height of parent layout . i.e. width or height of ScrollView will be same as width or height of parent layout.
- Fixed Value: Sets width or height as per value provided.
Set Padding of ScrollView
Follow steps below to set padding of ScrollView Dynamically –
- If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
- Now, we can set padding of ScrollView dynamically, in MainActivity.kt file, as –
Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of ScrollView using setPadding() method.
Set Margin of ScrollView
Follow steps below to set margin of ScrollView Dynamically –
- If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
- Now, we can set margin of ScrollView dynamically, in MainActivity.kt file, as –
Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, we have defined layoutParams, set margin to layoutParams. After that, set layoutParams to ScrollView.
Set Background of ScrollView
Follow steps below to set background of ScrollView programmatically –
- If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
- Now, we can set background of ScrollView dynamically, in MainActivity.kt file, as –
Here, we used setBackgroundColor() method to set background color in scrollView.
Set Visibility of ScrollView
We can set visibility of ScrollView programmatically as –
Here, we have set visibility of ScrollView using scrollView.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of ScrollView Using XML Attribute
That’s end of tutorial on ScrollView Programmatically in Kotlin With Example.
Источник
Tutorialwing
In this article, we will learn about android ScrollView using Kotlin. We will go through various example that demonstrates how to use different attributes of ScrollView. For example,
In this article, we will get answer to questions like –
- What is ScrollView?
- Why should we consider ScrollView while designing ui for any app?
- What are possibilities using ScrollView while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Tutorialwing Kotlin ScrollView Output
Tutorialwing Kotlin ScrollView Output
Getting Started
We can define android ScrollView widget as below –
ScrollView is a widget that are used to define vertically scrollable views. It can have only one direct child. So, if you need multiple child views, create a viewGroup as direct child of scrollView. Then, define all the views inside this viewGroup.
Now, how do we use ScrollView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as ScrollView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android ScrollView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access view in Kotlin file without using findViewById() method.
Using ScrollView in Kotlin
Follow steps below to use ScrollView in newly created project –
- We need some images, stored in res/drawable folder, to be used in the application. These drawable images will be used by child view of scrollView to create different views.
- Open res/values/strings.xml file. Then, add below code into it.
- Open res/layout/activity_main.xml file. Then, add below code in it –
- We can also access it in Kotlin File, MainActivity.kt, as below –
Now, run the application. We will get output as below –
Tutorialwing Kotlin ScrollView Output
Tutorialwing Kotlin ScrollView Output
Different Attributes of ScrollView in XML
Now, we will see how to use different attributes of Android ScrollView using Kotlin to customise it –
Set Id of ScrollView
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ScrollView using android:id attribute like below –
Here, we have set id of ScrollView as scrollView_ID using android:id=”” attribute. So, if we need to reference this ScrollView, we need to use this id – scrollView_ID.
Learn to Set ID of ScrollView Dynamically
Set Width of ScrollView
We use android:layout_width=”” attribute to set width of ScrollView.
We can do it as below –
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of ScrollView Dynamically
Set Height of ScrollView
We use android:layout_height=”” attribute to set height of ScrollView.
We can do it as below –
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of ScrollView Dynamically
Set Padding of ScrollView
We use android:padding=”” attribute to set padding of ScrollView.
We can do it as below –
Here, we have set padding of 10dp in ScrollView using android:padding=”” attribute.
Learn to Set Padding of ScrollView Dynamically
Set Margin of ScrollView
We use android:layout_margin=”” attribute to set margin of ScrollView.
We can do it as below –
Here, we have set margin of 10dp in ScrollView using android:layout_margin=”” attribute.
Learn to Set Margin of ScrollView Dynamically
Set Background of ScrollView
We use android:background=”” attribute to set background of ScrollView.
We can do it as below –
Here, we have set background of color #ff0000 in ScrollView using android:background=”” attribute.
Learn to Set Background of ScrollView Dynamically
Set Visibility of ScrollView
We use android:visibility=”” attribute to set visibility of ScrollView.
We can do it as below –
Here, we have set visibility of ScrollView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ScrollView Dynamically
Till now, we have see how to use android ScrollView using Kotlin. We have also gone through different attributes of ScrollView to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android ScrollView Widget
Below are the various attributes that are used to customise android ScrollView Widget. However, you can check the complete list of attributes of ScrollView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Some of the popular attributes of android scrollView widget are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:fillViewport | Defines whether scrollView should stretch it’s content to fill the viewport |
Some of the popular attributes of android ScrollView inherited from FrameLayout are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:foregroundGravity | Defines gravity of the foreground drawable |
2 | android:measureAllChildren | Defines whether to measure all children or only those in VISIBLE or INVISIBLE state when measuring |
Some of the popular attributes of ScrollView inherited from ViewGroup are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:animateLayoutChanges | Defines whether LayoutTransition should run whenever there is any changes in layout |
2 | android:animationCache | Defines whether layout animations should create a drawing cache for their children. |
3 | android:clipToPadding | Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero. |
4 | android:layoutAnimation | Defines the layout animation to use the first time the ViewGroup is laid out |
5 | android:layoutMode | Defines the layout mode of this viewGroup |
Some of the popular attributes of android ScrollView inherited from View are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:alpha | Defines the alpha of the view |
2 | android:background | Defines the background of the view |
3 | android:padding | Defines padding of the view for all edges |
4 | android:tooltipText | Defines text displayed in a small popup window on hover or long press |
5 | android:clickable | Defines whether view is clickable or not |
6 | android:theme | Defines a theme override for view |
7 | android:id | Defines id of the view |
8 | android:padding | Defines padding of the view |
We have seen different attributes of ScrollView and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is ScrollView, how can we use android ScrollView using Kotlin ? etc. We also went through different attributes of android ScrollView.
Источник