Muhammad Ibrahim
Muhammad Ibrahim

Reputation: 317

Collapsing TopAppBar in Jetpack Compose Material 3

I want to create a Collapsing TopAppBar as shown in the below Image. Left side when the TopAppBar is expanded and right side when collapsed. But I am unable to understand how to implement this Collapsing Top App Bar using Material 3 in Jetpack Compose.

I'll appreciate any help.

enter image description here

Upvotes: 2

Views: 199

Answers (1)

pieljo
pieljo

Reputation: 41

To build a collapsing toolbar in Jetpack compose I would recommend a Motionlayout.

Here is a good article that explains the Layout in Detail and also how to implement custom attribute changes.

https://medium.com/mindful-engineering/after-going-through-this-blog-youll-achieve-this-kind-of-polished-animation-using-motionlayout-6b76ec41c6ab

But to quickly some up the article. You need to define your TopBar as a MotionLayout.

 val context = LocalContext.current
 val motionScene = remember {
    context.resources
        .openRawResource(R.raw.motion_scene)
        .readBytes()
        .decodeToString()
 }

 MotionLayout(
    motionScene = MotionScene(motionScene),
    //as Progress you could use your Scrollindex of your LazyColumn
    progress = progress
) {
  //Put your UI-Elements here
  //add .layoutId() modifier to every element you want to change
}

Your R.raw.motion_scene should look like this. Here The FirstID-Element is getting bigger, changes its color and moves in the middle of its parent Element

{
  ConstraintSets: {
    //How the TopBar should look like at progress = 0 
    start: {
      FirstID: {
        width: 40,
        height: 40,
        start: ['parent', 'start', 16],
        top: ['parent', 'top', 16],
        /**here you can define custom properties that you can access in your 
        layout code with 
        motionProperties(id = "FirstID").value.color("background")**/
        custom: {
          background: '#08ff04',
          dicke: 2
        }
      }
    },
    //How the TopBar should look like at progress = 1
    end: {
      FirstID: {
        width: 150,
        height: 150,
        start: ['parent', 'start'],
        end: ['parent', 'end'],
        top: ['parent', 'top', 16],

        custom: {
          background: '#FFFFFF',
          dicke: 8
        }
      }
    }
  },
  //here you can define special Transitions of certain Elements 
  Transitions: {
    default: {
      from: 'start',
      to: 'end',
      pathMotionArc: 'startHorizontal',
      KeyFrames: {
        KeyAttributes: [
          {
            target: ['AnotherID'],
            frames: [0, 55, 100 ],
            translationX: [0, 75, 0],
            rotationX: [0, 180 , 360],
          }
        ]
      }
    }
  }
}

Upvotes: 1

Related Questions