문제 2.
- [①] 스크롤을 최상단으로 이동시키는 플로팅 버튼 기능 추가
- [②] 플로팅 버튼은 스크롤을 아래로 내릴 때 나타나며, 스크롤이 최상단일때 사라집니다.
- [③] 플로팅 버튼을 누르면 스크롤을 최상단으로 이동시킵니다.
- [④] 플로팅 버튼은 나타나고 사라질때 fade 효과가 있습니다.
- [⑤] 플로팅 버튼을 클릭하면(pressed) 아이콘 색이 변경됩니다
1. FloatingActionButton (플로팅 버튼)
① 스크롤을 최상단으로 이동시키는 플로팅 버튼 기능 추가
1. FloatingActionButton 설정
- buildgradle.kts
dependencies {
implementation("com.google.android.material:material:")
}
- 변경 사항
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
//http://schemas.android.com/app 확인 후 위와 같이 변경
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</androidx.constraintlayout.widget.ConstraintLayout>
2. FloatingActionButton 속성
- android:tint = "내부아이콘 색"
- app:maxImageSize = " 내부아이콘 크기 변경"
![]() |
![]() |
- android:backgroundTint = "버튼 배경색"
- app:fabSize = "버튼 크기 변경"
![]() |
![]() |
- android:layout_gravity = "RelativeLayout, LinearLayout 등에 위치를 지정할 때 사용"
- end|bottm : 오른쪽 아래
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="15dp"
android:layout_marginBottom="15dp"
android:backgroundTint="@color/black"
android:contentDescription="EDIT"
android:src="@drawable/baseline_arrow_upward_24"
android:tint="@color/white"
android:elevation="5dp"
app:fabSize="mini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
3. FloatingActionButton 사용법
- RecyclerView의 Scroll 상태 변화에 따라 감지 : RecyclerView.OnScrollListener()
//MainActivity.kt
binding.rcView.addOnScrollListener(object :RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
})
- 최상단 판별
- canScrollVertically(-1) : 수직, 최상단일 경우 false 값 return
- canScrollVertically(1) : 수직, 최하단일 경우 false 값 return
- 스크롤 상태
- RecyclerView.SCROLL_STATE_IDLE : 현재 스크롤이 되고 있지 않은 상태
- RecyclerView.SCROLL_STATE_DRAGGING : 현재 사용자의 터치(입력)와 같은 외부 입력에 영향
- RecyclerView.SCROLL_STATE_SETTLING : 현재 외부 제어 하에 있지 않은 상태에서 최종 위치로 애니메이션 작업을 수행
if (!binding.rcView.canScrollVertically(-1)
//최상단에서의 역할 감시(true)
&& newState == RecyclerView.SCROLL_STATE_IDLE)
//리사이클러뷰 스크롤과 중혹 허용되지 않게 스크롤 되지 않는 상태
② 플로팅 버튼은 스크롤을 아래로 내릴 때 나타나며, 스크롤이 최상단일때 사라짐
var isTop = true
binding.rcView.addOnScrollListener(object :RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!binding.rcView.canScrollVertically(-1) && newState == RecyclerView.SCROLL_STATE_IDLE){
binding.fab.visibility = View.GONE
isTop = true
}else{
if(isTop) {
binding.fab.visibility = View.VISIBLE
isTop = false
}
}
}
})
③ 플로팅 버튼을 누르면 스크롤을 최상단으로 이동
binding.fab.setOnClickListener {
binding.rcView.smoothScrollToPosition(0)
//0번째 항목으로 이동
}
④ 플로팅 버튼은 나타나고 사라질때 fade 효과
- 애니메이션 객체 생성
- AlphaAnimation : 투명도를 조절하여 애니메이션 구현
- ScaleAnimation : 크기를 조절하여 애니메이션 구현
- TranslateAnimation : 이동 애니메이션 구현
val fadeIn = AlphaAnimation(0f, 1f).apply { duration = 500 }
//duration : 애니메이션 동작시간
val fadeOut = AlphaAnimation(1f, 0f).apply { duration = 500 }
var isTop = true
binding.rcView.addOnScrollListener(object :RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!binding.rcView.canScrollVertically(-1) && newState == RecyclerView.SCROLL_STATE_IDLE){
binding.fab.startAnimation(fadeOut)
binding.fab.visibility = View.GONE
isTop = true
}else{
if(isTop) {
binding.fab.visibility = View.VISIBLE
binding.fab.startAnimation(fadeIn)
isTop = false
}
}
}
})
⑤ 플로팅 버튼을 클릭하면(pressed) 아이콘 색이 변경
- res > color > floation_btn : 플로팅 버튼을 눌렀을 때 버튼의 색상이 변경되는 xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/gray" android:state_pressed="true" />
//눌렀을 때
<item android:color="@color/black" android:state_enabled="true" />
//기본 상태
</selector>
- activity_main.xml > backgroundTint 변경
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="15dp"
android:layout_marginBottom="15dp"
android:backgroundTint="@color/floating_btn"
//@color/blach > floating_btn 변경
android:contentDescription="EDIT"
android:src="@drawable/baseline_arrow_upward_24"
android:tint="@color/white"
android:elevation="5dp"
app:fabSize="mini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
[Android/Kotlin] RecyclerView Move to Top - 최상단 이동 (tistory.com)
[Android/Kotlin] RecyclerView Move to Top - 최상단 이동
1. 요약 이번 글에서는 RecyclerView 리스트의 최상단으로 이동하도록 동작하는 버튼을 만드는 방법에 관하여 기술한다. 버튼은 애니메이션을 적용하여서 최상단이 아닐 경우 점점 나타나도록 만들
notepad96.tistory.com
'연습장 > 실습' 카테고리의 다른 글
6주차_ Kakao API 활용 앱 1. ViewPager/TabLayout (0) | 2024.05.03 |
---|---|
Basic 6주차_ 1. Enum Class, Sealed Class 사용 (1) | 2024.05.01 |
5주차_ 짝퉁마켓 앱 4. Parcelize 데이터 전달 (0) | 2024.04.16 |
5주차_ 짝퉁마켓 앱 2. 다이얼로그 & OnBackPressedCallback (0) | 2024.04.16 |
5주차_ 짝퉁마켓 앱 1. RecyclerView (0) | 2024.04.15 |