【问题标题】:How to programmatically change the state of a switch without triggering OnCheckChanged listener Android Studio如何以编程方式更改开关的状态而不触发 OnCheckChanged 监听器 Android Studio
【发布时间】:2021-02-05 18:49:27
【问题描述】:

又是类似的问题link。但是线程很旧,可以弄清楚。我想改变 switchB 中的 switchA 的状态,反之亦然,但不想触发侦听器中的代码。只有在按下开关时才需要执行代码。 我做到了:

switchA.setOnCheckedChangeListener (null);
                switchA.setChecked(false);

但这会完全禁用 switchA 侦听器。如何在 agian 上打开/激活它?

谢谢。

【问题讨论】:

    标签: switch-statement state listener


    【解决方案1】:

    您可以再次拨打switchA.setOnCheckedChangeListener(this);:

    public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //This is the listener
            switchA.setOnCheckedChangeListener(this);
    
            //Disable the listener
            switchA.setOnCheckedChangeListener(null);
            //set state of Switch
            switchA.setChecked(false);
            //Enable the Listener again
            switchA.setOnCheckedChangeListener(this);
    
        }
    
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 2011-06-29
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      相关资源
      最近更新 更多