我有三个 NumberPickers
,我想检测它们的值何时更改。我目前将它们用于其他用途,所以我知道它们有效。当您切换 Id 时,我尝试像 onClickListener 一样进行操作,但 id 在这里不起作用
public class ..... implements OnValueChangeListener {
// Removed
NumberPicker np1;
// Get the id from xml
np1.setOnValueChangedListener(this);
NumberPicker np2;
// Get the id from xml
np2.setOnValueChangedListener(this);
NumberPicker np3;
// Get the id from xml
np3.setOnValueChangedListener(this);
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
Log.i("value changed", "true"); // This IS shown
switch (getView().getId()) { // I think this is wrong
case R.id.numberPicker1:
Log.i("value 1", "true"); // Not shown
break;
case R.id.numberPicker2s:
Log.i("value 2", "true"); // Not shown
break;
case R.id.numberPicker3:
Log.i("value 3", "true"); // Not shown
break;
}
}
}
我可以分别添加每个监听器,但我认为那样会很困惑。
最佳答案
您仅在您的第一个数字选择器 (np1) 上重复设置监听器
编辑:
好的,我明白了。如何在 onCreate 中将对 NumberPicker 对象的引用存储为 Activity 的成员变量,并仅匹配 onValueChanged 监听器中的对象,如下所示:
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
if(picker == np1) {
...
} else if(picker == np2) {
...
} ...
}
我猜你没有在上面的代码 fragment 中检索到正确的 View ID:
switch (getView().getId()) { // I think this is wrong
您应该改为在选择器参数上调用 getId:
switch(picker.getId())
关于android - 多个 OnValueChanged 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18192490/