3

我试图向 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();
}

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

4

2 回答 2

6

您必须OnCheckedChangeListenerCompoundButtonwith上注册setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener)

newOrSavedSwitch.setOnCheckedChangeListener(this);
于 2013-09-12T17:45:17.013 回答
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

于 2013-09-12T17:47:55.243 回答