본문 바로가기
내일배움캠프 (스파르타 코딩 클럽) 안드로이드 2기/TIL

[TIL] ViewPager2 TapLayout

by 키윤 2024. 1. 15.

📖 Today I Learned

🔮 ViewPager2 & TapLayout

탭 레이아웃과 뷰페이저 2를 동시에 적용시키면 아래 탭 두개를 누름에 따라 그 안의 뷰가 바뀌고 양 옆으로 밀어도 이동한다.

탭 레이아웃을 적용시킬 액티비티에 들어가는 코드:
- 뷰페이저 어댑터와 프래그먼트를 연결시켜 준다.
- registerOnPageChangeCallBack 화면에 호출 시켜주는 코드??
- 탭 레이아웃과 뷰페이저도 연결 탭에 들어가는 문자열도 추가

package com.example.contactapp.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.viewpager2.widget.ViewPager2
import com.example.contactapp.MyPageFragment
import com.example.contactapp.adaptor.ViewPager2Adapter
import com.example.contactapp.databinding.ActivityContactBinding
import com.example.contactapp.fragment.ContactListFragment
import com.google.android.material.tabs.TabLayoutMediator

class ContactActivity : AppCompatActivity() {
    private lateinit var binding: ActivityContactBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityContactBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initViewPager()

    }

    private fun initViewPager() {
        //ViewPager2 Adapter 셋팅
        var viewPager2Adapter = ViewPager2Adapter(this)
        viewPager2Adapter.addFragment(ContactListFragment())
        viewPager2Adapter.addFragment(MyPageFragment())

        //Adapter 연결
        binding.viewPagerContactActivitySwipe.apply {
            adapter = viewPager2Adapter

            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            })
        }

        //ViewPager, TabLayout 연결
        TabLayoutMediator(binding.tabLayoutContactActivitySwitch, binding.viewPagerContactActivitySwipe) { tab, position ->
            Log.e("YMC", "ViewPager position: ${position}")
            when (position) {
                0 -> tab.text = "연락처"
                1 -> tab.text = "마이페이지"
            }
        }.attach()
    }
}

뷰페이지 어댑터 클래스 ViewPager2Adapter.kt

package com.example.contactapp.adaptor

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

//ViewPager2Adapter.kt
class ViewPager2Adapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
    var fragments: ArrayList<Fragment> = ArrayList()

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

    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }

    fun addFragment(fragment: Fragment) {
        fragments.add(fragment)
        notifyItemInserted(fragments.size - 1)
        //TODO: notifyItemInserted!!
    }

    fun removeFragement() {
        fragments.removeLast()
        notifyItemRemoved(fragments.size)
        //TODO: notifyItemRemoved!!
    }

}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".activity.ContactActivity">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/color_code_2"
        app:title="@string/my_contacts"
        app:titleTextColor="@color/white" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager_contact_activity_swipe"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout_contact_activity_switch"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/color_code_4"
        app:tabIconTint="@color/grey"
        app:tabIndicatorColor="@color/color_code_3"
        app:tabSelectedTextColor="@color/color_code_2"
        app:tabTextColor="@color/black" />



</LinearLayout>

💡 알고리즘 - 코틀린 : 프로그래머스 코드 카타

  • 기사단원의 무기 136798

https://occhiolism.tistory.com/99

 

[프로그래머스 • 코틀린] 기사단원의 무기 #136798

#136798 🎄 Question ? https://school.programmers.co.kr/learn/courses/30/lessons/136798# 🧩 Thought Process 소수의 개수를 셈할 수 있는 함수를 따로 만들고 소수의 개수가 제한 수 보다 크면 공격 수를 무게로 더해준

occhiolism.tistory.com

 

🏆 Comments