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

Android使用com.ebanx:swipe-button时无法保存滑动按钮状态怎么办?

问题原因

  • 布局加载顺序错误:setContentView() 需要在 findViewById() 之前调用,你当前的代码先执行控件查找,此时还未加载布局,拿到的swipeButton是空对象,后续所有操作都不生效。
  • 组件状态设置方法错误:com.ebanx:swipe-button 组件修改状态不是调用系统原生的setActivated()方法,需要调用组件自带的setState()方法设置状态。

修正后实现代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 先加载布局,再查找控件
    setContentView(R.layout.activity_attendance);
    swipeButton = findViewById(R.id.swipe_button);

    // 读取SharedPreferences存储的状态
    SharedPreferences tog_prefs = getSharedPreferences("save", MODE_PRIVATE);
    boolean pref_1 = tog_prefs.getBoolean("pref_1", false);
    // 调用组件自带的setState方法设置状态,第二个参数控制是否展示切换动画,初始化场景可传false
    swipeButton.setState(pref_1, false);

    swipeButton.setOnStateChangeListener(new OnStateChangeListener() {
        @Override
        public void onStateChange(boolean active) {
            SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
            editor.putBoolean("pref_1", active);
            // 用apply替代commit,异步写入不会阻塞主线程
            editor.apply();
            Toast.makeText(Attendance.this, active ? "打卡成功" : "已取消打卡", Toast.LENGTH_LONG).show();
        }
    });
}

可选优化点

  • 存储状态时无需重复写if-else判断,直接存回调返回的active参数即可
  • 如果有跨页面即时同步状态的需求,可以在onResume()生命周期里也增加一次状态读取刷新的逻辑,避免其他页面修改了打卡状态后当前页没有更新

内容的提问来源于stack exchange,提问作者Essiw Sined

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 11:24:03