如何将侦听器添加到切换按钮?

时间:2013-09-12 17:42:34

标签: java android switch-statement oncheckedchanged

我试图向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中的错误。

2 个答案:

答案 0 :(得分:6)

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

newOrSavedSwitch.setOnCheckedChangeListener(this);

答案 1 :(得分: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