【问题标题】:How to add a listenner to a Switch Button?如何将侦听器添加到切换按钮?
【发布时间】:2013-09-12 17:42:34
【问题描述】:

我正在尝试向 Switch 添加一个侦听器,但由于某种原因它不侦听检查事件。

我在我的活动中实现了CompoundButton.OnCheckedChangeListener,如下所示:

public class MyActivity extends Activity 
           implements CompoundButton.OnCheckedChangeListener 

这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);

    newOrSavedSwitch = (Switch)  findViewById(R.id.new_or_saved_switch);        
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   Toast.makeText(this, "Monitored switch is " + (isChecked ? "on" : "off"),
           Toast.LENGTH_SHORT).show();
}

toast 没有显示,我也没有在 logcat 中看到错误。

【问题讨论】:

    标签: java android switch-statement oncheckedchanged


    【解决方案1】:

    您必须使用setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener)OnCheckedChangeListener 注册到CompoundButton

    newOrSavedSwitch.setOnCheckedChangeListener(this);
    

    【讨论】:

      【解决方案2】:

      使用 setOnCheckedChangeListener(this) 方法注册开关。

      你可以尝试只使用内部类类型的监听器

       toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                      if (isChecked) {                   
                          Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!", Toast.LENGTH_LONG).show();
                      } else {                   
                          Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!", Toast.LENGTH_LONG).show();
                      }
                  }
              });
      

      这对我很有用。

      您可能还想看看这个帖子Android Switch Example

      【讨论】:

      • +1 替代答案,顺便问一下,这样做有什么区别?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2015-02-04
      • 2011-08-21
      • 2011-07-20
      • 1970-01-01
      • 2023-03-24
      • 2017-07-13
      相关资源
      最近更新 更多