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

实现滑动按钮时遇动画崩溃:ERROR: 'this' is not available 求助

解决滑动按钮动画中的'this' is not available错误及左滑实现修正

看起来你遇到的'this' is not available错误,大概率是因为动画初始化的时机不对——比如你在Activity/Fragment的生命周期还没准备好的时候(比如类成员变量直接初始化阶段)就创建了ValueAnimator,或者错误地在静态上下文里引用了this。结合你要实现按钮左滑的需求,我整理了完整的修正方案:

错误根源分析

  • 如果你把mButtonTranslator作为类成员变量直接赋值(比如在类的顶部直接写private ValueAnimator mButtonTranslator = ValueAnimator.ofInt(0,90);),这时候Activity的this上下文还没完成初始化,就会触发这个错误。
  • 另外你当前的动画参数0,90是让按钮向右滑动(translationX正值代表向右偏移),和你要的左滑需求不符,需要调整数值范围。

修正后的完整代码示例

在Activity中实现

private ValueAnimator mButtonTranslator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    // 先获取按钮实例
    Button button1 = findViewById(R.id.button1);
    
    // 初始化左滑动画:从0偏移到-90(负值代表向左)
    mButtonTranslator = ValueAnimator.ofInt(0, -90);
    mButtonTranslator.setDuration(300); // 设置动画时长,单位毫秒,让滑动更流畅
    mButtonTranslator.addUpdateListener(animatedValue -> {
        int offsetDistance = (int) animatedValue.getAnimatedValue();
        button1.setTranslationX(offsetDistance);
    });
    
    // 给按钮绑定点击事件,触发动画
    button1.setOnClickListener(v -> {
        // 避免重复点击导致动画混乱,先判断动画是否正在运行
        if (!mButtonTranslator.isRunning()) {
            mButtonTranslator.start();
        }
    });
}

在Fragment中实现

如果是在Fragment里,要等到View加载完成后再初始化动画,也就是放到onViewCreated方法里:

private ValueAnimator mButtonTranslator;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Button button1 = view.findViewById(R.id.button1);
    
    mButtonTranslator = ValueAnimator.ofInt(0, -90);
    mButtonTranslator.setDuration(300);
    mButtonTranslator.addUpdateListener(animatedValue -> {
        int offsetDistance = (int) animatedValue.getAnimatedValue();
        button1.setTranslationX(offsetDistance);
    });
    
    button1.setOnClickListener(v -> {
        if (!mButtonTranslator.isRunning()) {
            mButtonTranslator.start();
        }
    });
}

额外注意点

  • 如果你的mButtonTranslator被声明为static变量,一定要改成非静态成员变量——静态变量属于类本身,无法引用实例级别的this上下文,这也是常见的触发该错误的原因。
  • 如果你需要让按钮滑回原位,可以再创建一个反向动画(从-90到0),或者调用mButtonTranslator.reverse()方法。

内容的提问来源于stack exchange,提问作者Mark Caveneau

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:45:30