본문 바로가기

Android

ViewPager를 이용한 Fragment전환, TabLayout(2) - Indicator

· viewpager를 통한 화면전환과 tablayout연동을 통한 indicator dots

1) 먼저 activity에 ViewPager와 TabLayout을 만들어준다

<?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:id="@+id/constraintlayout_fragment_one"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentOne">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager_ad"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/indicator_ad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="@id/viewpager_ad"
        app:layout_constraintBottom_toBottomOf="@id/viewpager_ad"
        app:layout_constraintEnd_toEndOf="@id/viewpager_ad"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@id/viewpager_ad"
        app:layout_constraintVertical_bias="0.9"
        app:tabBackground="@drawable/inidicator"
        app:tabGravity="center"%
        app:tabIndicatorHeight="0dp" />


</androidx.constraintlayout.widget.ConstraintLayout>

2) ViewPager에 들어갈 Fragment를 생성해주고 xml파일을 용도에 맞게 꾸며준다.(fragment_advertisement)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:id="@+id/imageview_advertisement"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

3) drawable 파일에 indicator.xml을 만들어준다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <shape
            android:shape="ring"
            android:innerRadius="0dp"
            android:thickness="6dp"
            android:useLevel="false">
            <solid android:color="@android:color/darker_gray"/>
        </shape>
    </item>
    <item android:state_selected="true">
        <shape
            android:shape="ring"
            android:innerRadius="0dp"
            android:thickness="6dp"
            android:useLevel="false">
            <solid android:color="@android:color/holo_orange_light"/>
        </shape>
    </item>
</selector>

 

4) PagerAdapter를 만들어준다.

class AdvertisementPagerAdapter(fm: FragmentManager, private val page_count : Int): FragmentStatePagerAdapter(fm){

    override fun getItem(position: Int): Fragment {

        val advertisementFragment = AdvertisementFragment()
        val bundle = Bundle(page_count)
        bundle.putInt("id", position)
        advertisementFragment.arguments = bundle

        return advertisementFragment
    }

    override fun getCount() : Int = page_count
}

 

5) Fragment마다 띄울 뷰를 지정해준다.

class AdvertisementFragment : BaseFragment(){
    var advertisementId: Int = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_advertisement, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        advertisementId = arguments!!.getInt("id")
        init()
    }
    private fun init() {
        when(advertisementId){
            0 ->{
                 imageview_advertisement.setImageResource(R.drawable.positano)
            }

            1 -> {
                imageview_advertisement.setImageResource(R.drawable.paris)
            }
            2 -> {
                imageview_advertisement.setImageResource(R.drawable.bern)
            }
        }
    }
}

 

6) Activity에서 ViewPager에 Adapter를 연결해준다.

class PosterActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_poster)

        val adapter = AdvertisementPagerAdapter(supportFragmentManager, 3)
        viewpager_ad.adapter = adapter
        viewpager_ad.offscreenPageLimit = 2
        indicator_ad.setupWithViewPager(viewpager_ad)
    }
}

 

7) 이렇게만 해도 indicator가 완성되지만 tablayout의 특성상 인디케이터를 터치하면 다음 뷰로 전환이 된다. 만약 터치가 안되게 하고 싶으면 하단의 코드처럼 disabledTab함수를 추가해 적용해주면 된다.

class PosterActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_poster)

        val adapter = AdvertisementPagerAdapter(supportFragmentManager, 3)
        viewpager_ad.adapter = adapter
        viewpager_ad.offscreenPageLimit = 2
        indicator_ad.setupWithViewPager(viewpager_ad)
        disabledTab(indicator_ad!!, 3)
    }

    private fun disabledTab(tabLayout: TabLayout, index: Int){
        Handler().postDelayed(Runnable {
            val tabStrip = tabLayout.getChildAt(0) as ViewGroup
            for(i in 0 until tabStrip.childCount){
                tabStrip.getChildAt(i).isEnabled = false
            }
        }, 100)
    }
}

'Android' 카테고리의 다른 글

🔍 Data Binding with Retrofit (Kakao 웹문서 검색 API)  (0) 2021.02.06
Android Studio WebView  (0) 2020.09.21
Android CheckBox (회원가입 화면)  (0) 2020.09.21
Android Spinner만들기(Kotlin)  (0) 2020.09.10
Activity Task 관리하기  (0) 2020.09.10