Design-loving front-end engineer
Ryong
Design-loving front-end engineer
전체 방문자
오늘
어제
    • Framework
    • React
      • Concept
      • Library
      • Hook
      • Component
      • Test
    • NodeJS
    • Android
      • Concept
      • Code
      • Sunflower
      • Etc
    • Flutter
      • Concept
      • Package
    • Web
    • Web
    • CSS
    • Language
    • JavaScript
    • TypeScript
    • Kotlin
    • Dart
    • Algorithm
    • Data Structure
    • Programmers
    • Management
    • Git
    • Editor
    • VSCode
    • Knowledge
    • Voice
Design-loving front-end engineer

Ryong

[Android] [Kotlin] ViewPager (뷰페이저)
Android/Concept

[Android] [Kotlin] ViewPager (뷰페이저)

2021. 9. 13. 22:07

ViewPager2 + Fragment + TabLayout

✔  각각 화면들이 독립적으로 구성될 필요가 있을 때 Fragment 사용

UI

 

전체 코드

MainActivity.kt

더보기
더보기
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(binding.root)

        val fragmentList = listOf(FragmentA(), FragmentB(), FragmentC(), FragmentD())
        val adapter = FragmentAdapter(this)
        adapter.fragmentList = fragmentList
        binding.viewPager.adapter = adapter

        // 소스 코드에서 TabLayout 설정하기
        val tabTitles = listOf<String>("A", "B", "C", "D")
        // TabLayout과 뷰페이저 연결
        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.text = tabTitles[position]
        }.attach()
    }
}

 

FragmentAdapter.kt

더보기
더보기
class FragmentAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
    var fragmentList = listOf<Fragment>()  // 개수가 변하지 않기 때문에 mutable을 사용하지 않음

    // 화면에 보여줄 전체 프래그먼트의 개수 반환
    override fun getItemCount(): Int {
        return fragmentList.size
    }

    // 현재 페이지의 position이 파라미터로 넘어온다. position에 해당하는 위치의 프래그먼트를 만들어서 안드로이드에 반환
    override fun createFragment(position: Int): Fragment {
        return fragmentList[position]
    }
}

 

activity_main.xml

더보기
더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

<!-- layout에서 Tablayout 설정하기 -->
<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="Monday" />-->
 
<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="Tuesday" />-->
 
<!--        <com.google.android.material.tabs.TabItem-->
<!--            android:layout_width="wrap_content"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:text="Wednesday" />-->
 
    </com.google.android.material.tabs.TabLayout>
 
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
 
cs

 

ViewPager2 + View + TabLayout

✔  반복적으로 동일한 구조의 텍스트나 이미지를 보여줄 때는 뷰를 사용

UI

 

전체 코드

MainActivity.kt

더보기
더보기
class MainActivity : AppCompatActivity() {

    val binding by lazy {ActivityMainBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val textList = listOf("뷰A", "뷰B", "뷰C", "뷰D")
        val customAdapter = CustomPagerAdapter()
        customAdapter.textList = textList
        binding.viewPager.adapter = customAdapter

        val tabTitles = listOf("View A", "View B", "View C", "View D")
        TabLayoutMediator(binding.tabLayout, binding.viewPager) {tab, position ->
            tab.text = tabTitles[position]
        }.attach()
    }
}

 

CustomPagerAdapter.kt

더보기
더보기
class CustomPagerAdapter : RecyclerView.Adapter<Holder>(){
    var textList = listOf<String>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val binding = ItemViewpagerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return Holder(binding)
    }

    override fun getItemCount(): Int {
        return textList.size
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val text = textList[position]
        holder.setText(text)
    }
}

class Holder(val binding: ItemViewpagerBinding) : RecyclerView.ViewHolder(binding.root) {
    fun setText(text:String) {
        binding.textView.text = text
    }
}

 

activity_main.xml

더보기
더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
        
    </com.google.android.material.tabs.TabLayout>
 
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout" />
    
</androidx.constraintlayout.widget.ConstraintLayout>
 
cs

 

item_viewpager.xml

더보기
더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="여기제목"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs
저작자표시

'Android > Concept' 카테고리의 다른 글

[Android] [Kotlin] SharedPreferences  (0) 2021.09.19
[Android] [Kotlin] SQLite  (0) 2021.09.14
[Android] [Kotlin] 인텐트  (0) 2021.09.12
[Android] [Kotlin] 생명주기  (0) 2021.09.12
[Android] [Kotlin] 리사이클러뷰  (0) 2021.09.01
    'Android/Concept' 카테고리의 다른 글
    • [Android] [Kotlin] SharedPreferences
    • [Android] [Kotlin] SQLite
    • [Android] [Kotlin] 인텐트
    • [Android] [Kotlin] 생명주기
    Design-loving front-end engineer
    Design-loving front-end engineer
    디자인에 관심이 많은 모바일 앱 엔지니어 Ryong입니다.

    티스토리툴바