이번 시간에는 버튼을 추가해서 ViewPager2 화면을 앞, 뒤로 변경하는 방법을 알아보겠습니다.
이전 포스팅에 이어서 하니 아래 링크를 먼저 보시면 됩니다.
2022.06.22 - [분류 전체보기] - [안드로이드 코틀린] 밀어서 화면 변경 ViewPager2 화면 변경 위치 표시(Indicator) 직접 만드는 방법
[안드로이드 코틀린] 밀어서 화면 변경 ViewPager2 화면 변경 위치 표시(Indicator) 직접 만드는 방법
이전 포스팅에 ViewPager2에 라이브러리를 통해 화면 위치 표시를 구현했습니다. 이번 시간에는 라이브러리 없이 직접 구현하는 방법에 대하여 알아보겠습니다. 이전에 만든 것을 수정하기 때문에
aries574.tistory.com
build.gradle(Module:프로젝트명:app)
dependencies 괄호 안에 아래 코드를 넣어주시면 됩니다.
implementation 'com.google.android.material:material:1.6.1'
material 테마로 변경
( res -> value -> themes)
<style name="Theme.KotlinExam" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
- 설명 -
1. 레이아웃 배경 색상과 텍스트뷰 텍스트 색상을 변경합니다.
2. 색상 추가
색상 res -> values -> colors.xml
<color name="gray_700">#616161</color>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_700"
tools:context=".OneFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="50sp"
android:textColor="@android:color/white"
android:text="화면1" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_700"
tools:context=".TwoFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="화면2"
android:textColor="@android:color/white"
android:textSize="50sp" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_700"
tools:context=".ThreeFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="화면3"
android:textColor="@android:color/white"
android:textSize="50sp" />
</FrameLayout>
- 설명 -
viewPager2의 화면을 변경해줄 Button 추가
<?xml version="1.0" encoding="utf-8"?>
<layout 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"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- 화면 위치 표시 -->
<LinearLayout
android:id="@+id/dotsLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:orientation="horizontal" />
<!-- Back버튼 -->
<com.google.android.material.button.MaterialButton
android:id="@+id/btnBack"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="15dp"
android:layout_marginBottom="80dp"
android:text="@string/back"
android:textColor="@android:color/white"
app:rippleColor="@android:color/white"/>
<!-- Next 버튼-->
<com.google.android.material.button.MaterialButton
android:id="@+id/btnNext"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="15dp"
android:layout_marginBottom="80dp"
android:text="@string/next"
android:textColor="@android:color/white"
app:rippleColor="@android:color/white"/>
</RelativeLayout>
</layout>
- 설명 -
1. currentPage
현재 위치 담을 변수
2. viewPager2.currentItem
ViewPager2 페이지 변경
3. when (position)
페이지에 따른 버튼 상태 변경
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
//텍스트뷰
private var dots = arrayOfNulls<TextView>(3)
//페이지 위치
private var currentPage = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//binding 초기화
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
//프래그먼트 선언
var fragment1 = OneFragment()
var fragment2 = TwoFragment()
var fragment3 = ThreeFragment()
//리스트에 프래그먼트 등록
var fragments = ArrayList<Fragment>()
fragments.add(fragment1)
fragments.add(fragment2)
fragments.add(fragment3)
//PageAdapter에 리스트를 등록
var adapter = PageAdapter(this, fragments)
//ViewPager2에 Adapter 적용
binding.viewPager2.adapter = adapter
//화면 위치 표시
dotsIndicator()
//화면 변경 시 이벤트 설정
binding.viewPager2.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback(){
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
//화면 위치 표시 색상 설정
selectedIndicator(position)
//변수에 현재 위치 담기
currentPage = position
when(position){
0 -> { //첫 페이지
binding.btnNext.isEnabled = true //활성화
binding.btnBack.isEnabled = false //비활성화
binding.btnBack.visibility = View.INVISIBLE //숨김
binding.btnNext.text = getString(R.string.next)
binding.btnBack.text = ""
}
dots.size -1 -> { //마지막 페이지
binding.btnNext.isEnabled = false //비활성화
binding.btnBack.isEnabled = true //활성화
binding.btnBack.visibility = View.VISIBLE //보이기
binding.btnNext.text = getString(R.string.end)
binding.btnBack.text = getString(R.string.back)
}
else -> { //중간
binding.btnNext.isEnabled = true //비활성화
binding.btnBack.isEnabled = true //활성화
binding.btnBack.visibility = View.VISIBLE //보이기
binding.btnNext.text = getString(R.string.next)
binding.btnBack.text = getString(R.string.back)
}
}
}
})
//Back버튼 이벤트
binding.btnBack.setOnClickListener {
//ViewPage2 화면 변경
binding.viewPager2.currentItem = currentPage -1
}
//Next버튼 이벤트
binding.btnNext.setOnClickListener {
//ViewPage2 화면 변경
binding.viewPager2.currentItem = currentPage +1
}
}
//화면 위치 표시
private fun dotsIndicator(){
for(i: Int in 0 until 3){
dots[i] = TextView(this)
dots[i]?.text = Html.fromHtml(("●"), Html.FROM_HTML_MODE_LEGACY)
dots[i]?.textSize = 25F
//텍스트뷰 레이아웃 섲렁
var params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT
)
//텍스트뷰 거리 조절
params.leftMargin = 30
//텍스트뷰 레이아웃 적용
dots[i]?.layoutParams = params
//레이아웃에 텍스트뷰 적용
binding.dotsLayout.addView(dots[i])
}
}
//화면 위치 표시 색상 설정
private fun selectedIndicator(position: Int){
for(i: Int in 0 until 3){
if(i == position){
dots[i]?.setTextColor(ContextCompat.getColor(applicationContext, R.color.pink_200))
}else{
dots[i]?.setTextColor(ContextCompat.getColor(applicationContext, R.color.blue_200))
}
}
}
}
2022.06.14 - [안드로이드] - [안드로이드 코틀린] Tab Custom Animation part1 - 화면 구성 및 설정
[안드로이드 코틀린] Tab Custom Animation part1 - 화면 구성 및 설정
앞으로 TabLayout을 직접 만들어 애니메이션 기능까지 넣어보도록 하겠습니다. 이번 시간에는 화면 구성 및 설정을 만들어 보겠습니다. 목차 1. 실행 화면 2. dataBinding 설정 build.gradle 3. 테마 변경 t
aries574.tistory.com
2022.03.28 - [안드로이드] - [안드로이드] 숫자 맞추기 게임 Up&Down 만드는 방법 part1 - 화면 구성
[안드로이드] 숫자 맞추기 게임 Up&Down 만드는 방법 part1 - 화면 구성
이번 시간에는 랜덤한 숫자를 생성하면, 사용자는 숫자를 입력해서 맞추는 게임을 만들어 보려고 합니다. 물론 무작정 맞추는 게 아니라 입력한 숫자가 랜덤한 숫자보다 큰지, 작은지 정도는
aries574.tistory.com
2022.05.14 - [안드로이드] - [안드로이드] Database Room 사용법 part1 - Room 설정
[안드로이드] Database Room 사용법 part1 - Room 설정
Room 사용법을 알아보겠습니다. 앱 내부에 데이터를 관리하는 기능을 도와주는 라이브러리입니다. SQLite보다 쉽게 사용할 수 있습니다. 자세한 내용은 아래 링크를 가시면 보실 수 있습니다. https:
aries574.tistory.com
[안드로이드 코틀린] Database Room 사용법 part2 - 데이터 등록 (0) | 2022.06.25 |
---|---|
[안드로이드 코틀린] Database Room 사용법 part1 - Room 설정 (0) | 2022.06.24 |
[안드로이드 코틀린] 밀어서 화면 변경 ViewPager2 화면 변경 위치 표시(Indicator) 직접 만드는 방법 (0) | 2022.06.22 |
[안드로이드 코틀린] 밀어서 화면 변경 ViewPager2 화면 변경 위치 표시(Indicator) 해주는 방법 (0) | 2022.06.21 |
[안드로이드 코틀린] 밀어서 화면 변경 ViewPager2 갤러리 느낌으로 만드는 방법 (5) | 2022.06.20 |
댓글 영역