按谷歌指南实现共享元素过渡动画时遇空指针异常求助
Hey, let's work through this NullPointerException you're hitting while implementing shared element transitions following Google's guide. That error pointing to TransitionSet.setDuration() means the internal list of transitions in your TransitionSet instance is null—here are the most common fixes and pitfalls to avoid:
Ensure your TransitionSet is properly initialized and populated
If you're creating aTransitionSetprogrammatically, don't callsetDuration()(or other methods that modify the transition list) before adding at least one transition. The internalArrayListholding transitions only gets initialized when you add your first transition.
Bad code that triggers NPE:TransitionSet transitionSet = new TransitionSet(); transitionSet.setDuration(300); // Internal transitions list is null here!Fixed code:
TransitionSet transitionSet = new TransitionSet(); // Add at least one transition first transitionSet.addTransition(new ChangeBounds()); transitionSet.addTransition(new ChangeImageTransform()); transitionSet.setDuration(300); // Now safe to callAvoid empty Transition XML files
If you're inflating aTransitionSetfrom XML (usingTransitionInflater.from(context).inflateTransition(R.transition.your_set)), make sure your XML file contains at least one transition element. An empty XML will result in aTransitionSetwith a null internal transitions list.
Valid transition XML example:<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"> <changeBounds /> <changeImageTransform /> </transitionSet>Don't pass null TransitionSet instances to ActivityOptions
When setting upActivityOptionsfor your shared element transition, never pass a nullTransitionSetto methods likesetEnterTransition()orsetReturnTransition(). This can lead to the system trying to modify a null transition set later, triggering the NPE.Upgrade to AndroidX Transition library
This specific NPE was a known issue in older versions of the Android Support Transition library. If you're still usingandroid.support.transition, migrate toandroidx.transition(the modern replacement) or upgrade your Support Library to the latest stable version. AndroidX fixes many low-level edge cases like uninitialized transition lists.
Start with checking how you're creating and populating your TransitionSet—this is the root cause for most cases of this error. Double-checking your XML or ensuring you add transitions before modifying the set's duration should resolve the issue.
内容的提问来源于stack exchange,提问作者Merov

