You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按谷歌指南实现共享元素过渡动画时遇空指针异常求助

Fixing NullPointerException in TransitionSet.setDuration() for Shared Element Transitions

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 a TransitionSet programmatically, don't call setDuration() (or other methods that modify the transition list) before adding at least one transition. The internal ArrayList holding 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 call
    
  • Avoid empty Transition XML files
    If you're inflating a TransitionSet from XML (using TransitionInflater.from(context).inflateTransition(R.transition.your_set)), make sure your XML file contains at least one transition element. An empty XML will result in a TransitionSet with 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 up ActivityOptions for your shared element transition, never pass a null TransitionSet to methods like setEnterTransition() or setReturnTransition(). 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 using android.support.transition, migrate to androidx.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:33:30