본문 바로가기

IT/안드로이드 관련

[안드로이드] ValueAnimator를 이용한 애니메이션 사용해보기

SMALL

안녕하세요 남갯입니다.


오늘은 ValueAnimator와 ViewPager


 이용한 회원가입 Step 만들기를 포스팅 해보려고합니다.


일단 회원가입 화면을 만듭니다.






<?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:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/layoutRecordActionBar"
android:layout_width="match_parent"
android:layout_height="56dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">


<TextView
android:id="@+id/txtRecordTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="회원가입"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="회원가입" />


</androidx.constraintlayout.widget.ConstraintLayout>

<LinearLayout
android:id="@+id/layoutRecordProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:weightSum="0.3"
app:layout_constraintTop_toBottomOf="@+id/layoutRecordActionBar">

<View
android:id="@+id/viewRecordProgressColored"
android:layout_width="0dp"
android:layout_height="8dp"
android:layout_weight="0.1"
android:background="@color/colorPrimary" />

<View
android:id="@+id/viewRecordProgressNone"
android:layout_width="0dp"
android:layout_height="8dp"
android:layout_weight="0.2"
android:background="#cecece" />

</LinearLayout>


<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPagerRecord"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/layoutRecordProgressBar" />


</androidx.constraintlayout.widget.ConstraintLayout>



여기서 중요한건 자신의 Step에 맞게 weighSum의 값을 조절해야합니다.


저는 3스텝으로 했으니 0.3으로 지정했습니다.




class MainViewPagerAdapter(
fm: androidx.fragment.app.FragmentManager,
private val fragmentList: ArrayList<Fragment>
) : androidx.fragment.app.FragmentStatePagerAdapter(
fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
) {
override fun getItem(position: Int): Fragment = fragmentList[position]
override fun getCount(): Int = fragmentList.size
}


ViewPager Adapter를 만듭니다.




class MainFragment : Fragment() {

companion object {
lateinit var drunkFragment: MainFragment

fun newInstance(): MainFragment {
synchronized(MainFragment::class) {
drunkFragment = MainFragment()
val args = Bundle()
drunkFragment.arguments = args
return drunkFragment
}
}
}


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

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
initRecyclerView()
requestTodayDrunkList()
}

private fun initRecyclerView() {

}

private fun requestTodayDrunkList() {

}



}


뷰페이저니까 뷰페이저를 구성할 프래그먼트를 생성한 뒤


<?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="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">

<TextView
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello world!" />

</androidx.constraintlayout.widget.ConstraintLayout>


요건 xml


class MainActivity : AppCompatActivity() {

private var progressPosition = 1

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
}



private fun init() {
initEvent()
initViewPager()
}

private fun initEvent() {
}


private fun initViewPager() {
//서버로 부터 받아온 페이지수 추가
val fragmentList = ArrayList<Fragment>().apply {
add(MainFragment.newInstance())
add(MainFragment.newInstance())
add(MainFragment.newInstance())
}


viewPagerRecord.apply {
adapter = MainViewPagerAdapter(supportFragmentManager, fragmentList)
offscreenPageLimit = 3
currentItem = 0
addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}

override fun onPageSelected(position: Int) {
animateProgress(position)
}
})
}
}

//progressAnimate
fun animateProgress(position: Int) {
val coloredWidthProgressAnimator: ValueAnimator = ValueAnimator.ofFloat(
(PROGRESS_WEIGHT_STEP * progressPosition),
(PROGRESS_WEIGHT_STEP * (position + 1))
).apply {
duration = 300
addUpdateListener {
val value: Float = it.animatedValue as Float
(viewRecordProgressColored.layoutParams as (LinearLayout.LayoutParams)).weight =
value
viewRecordProgressColored.requestLayout()
}
}
coloredWidthProgressAnimator.start()
progressPosition = (position + 1)
}

companion object {
const val PROGRESS_WEIGHT_STEP = 0.1f
}
}



그 후 뷰페이저를 세팅하고 


valueAnimation을 세팅합니다.


아이템이 선택이 되면 animation을 동작시키도록 한 뒤

값이 변경됨에 따라 그 값에 맞춰 weight를 변경 하도록 합니다.


저는 아까 Sum = 0.3


0.1 -> 0.2 , 0.2 -> 0.3

색깔부분은 0.1로 초기 세팅을 했으니 시작값 -> 증가될값을 ValueAnimator에 세팅합니다.



해당 값이 업데이트 됨에따라 UpdateListener에서 weight를 변경하며 비율에 맞게 길이를 변경합니다.






코드는 아래의 링크에서 볼 수 있습니다


https://github.com/namget/ProgressAnimation


도움이 되셨다면 Star 부탁드립니다.



LIST