ViewPager2 & tabLayout 사용 방법
============xml================
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/tabLayout"
/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="0dp"
android:layout_height="55dp"
android:background="@color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:fillViewport="true"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorHeight="0dp"
app:tabPaddingBottom="0dp"
app:tabPaddingEnd="0dp"
app:tabPaddingStart="0dp"
app:tabPaddingTop="0dp"
/>
=============Adapter =================
class MainViewPagerAdapter(fa: FragmentActivity): FragmentStateAdapter(fa) {
private var listener: OnItemClickListener? = null
private var items: MutableList<BluetoothDevice> = arrayListOf()
fun setItemClickListener(listener: OnItemClickListener){
this.listener = listener
}
override fun getItemCount(): Int {
return MainTabItems.values().count()
}
override fun createFragment(position: Int): Fragment {
when(position){
MainTabItems.AREA.ordinal ->{
return HomeFragment()
}
MainTabItems.MYAROUND.ordinal ->{
return HomeFragment()
}
MainTabItems.CHAT.ordinal ->{
return HomeFragment()
}
MainTabItems.MYAPAGE.ordinal ->{
return HomeFragment()
}
else->{
return HomeFragment()
}
}
}
}
==============Main Source ==============
viewPager.apply {
adapter = mainViewPagerAdapter
}
TabLayoutMediator(tabLayout, viewPager){tab, position->
layoutInflater.inflate(R.layout.custom_main_tab_item, null).apply{
tvMainTab.text = when(position){
MainTabItems.AREA.ordinal ->{
R.string.main_tab_item2.toResString()
}
MainTabItems.MYAROUND.ordinal ->{
R.string.main_tab_item3.toResString()
}
MainTabItems.CHAT.ordinal ->{
R.string.main_tab_item4.toResString()
}
MainTabItems.MYAPAGE.ordinal ->{
R.string.main_tab_item5.toResString()
}
else ->{
R.string.main_tab_item1.toResString()
}
}
ivMainTab.background = when(position){
MainTabItems.AREA.ordinal ->{
R.drawable.ic_launcher_foreground.toDrawable()
}
MainTabItems.MYAROUND.ordinal ->{
R.drawable.ic_launcher_foreground.toDrawable()
}
MainTabItems.CHAT.ordinal ->{
R.drawable.ic_launcher_foreground.toDrawable()
}
MainTabItems.MYAPAGE.ordinal ->{
R.drawable.ic_launcher_foreground.toDrawable()
}
else ->{
R.drawable.ic_launcher_foreground.toDrawable()
}
}
tab.customView = this
}
}.attach()
'안드로이드' 카테고리의 다른 글
[Android] 블루투스(Bluetooth) 개발에 대해 알아보자 (0) | 2022.10.24 |
---|---|
[Android] 블루투스(Bluetooth) Gatt 개발 순서 (0) | 2022.10.24 |
[Android] viewpager setUserVisibleHint, swipe, transition, 양쪽 마진 (0) | 2022.10.24 |
[Android] 데이터 바인딩(DataBinding) (0) | 2022.10.24 |
[Android] Wifi 연결 및 가져오기 (0) | 2022.10.24 |