Home > other >  How Add Animation On view when view width is changing [Android]
How Add Animation On view when view width is changing [Android]

Time:12-24

I'm using collapsing toolbar and I am changing view width OnOffsetChangedListener. what I want is that put little animation when searchView width will change , now its changing very straight and its little weird for user. I tried to set android:animateLayoutChanges="true" on parent layout but it not worked

       var mListener =
        OnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (binding.collapsingToolbar.getHeight()   verticalOffset < 2 * ViewCompat.getMinimumHeight(
                    binding.collapsingToolbar
                )
            ) {
                val view: View = binding.searchView
                val layoutParams: CollapsingToolbarLayout.LayoutParams = view.layoutParams as CollapsingToolbarLayout.LayoutParams
               layoutParams.width = binding.appBar.width / 2
                view.layoutParams = layoutParams

            } else {

                val view: View = binding.searchView
                val layoutParams: CollapsingToolbarLayout.LayoutParams = view.layoutParams as CollapsingToolbarLayout.LayoutParams
                layoutParams.width = CollapsingToolbarLayout.LayoutParams.MATCH_PARENT
                view.layoutParams = layoutParams

            }
        }

    binding.appBar.addOnOffsetChangedListener(mListener)

CodePudding user response:

How you tried built-in interpolators?

Please check below link for some insights: https://jebware.com/interp/android-animation-interpolators.html

a very basic example is as follows:

        val fastOutSlowInInterpolator = FastOutSlowInInterpolator()
        
        val interpolatedValue = fastOutSlowInInterpolator.getInterpolation(0.5f)

In above example 0.5f would vary from 0 to 1 and it will return animated value which you should use in view animation.

CodePudding user response:

You can simply define an animation class.

class ResizeWidthAnimation(private val mView: View, private val mWidth: Int) : Animation() {
    private val mStartWidth: Int = mView.width

    override fun applyTransformation(interpolatedTime: Float, t: Transformation{
        mView.layoutParams.width = mStartWidth   ((mWidth - mStartWidth) * interpolatedTime).toInt()
        mView.requestLayout()
    }

    override fun willChangeBounds(): Boolean {
        return true
    }
}
  • Related