如何给开关按钮添加监听器?

3

我试图给开关添加一个监听器,但出于某些原因它无法监听到选中事件。

我在我的活动中实现了 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();
}

提示框没有弹出,同时我在日志中也没有看到任何错误信息。

2个回答

6

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 作为替代答案。 - meda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接