回调不是同步的。不幸的是,您不能简单地执行String abc = onCountryPickerClick();,因为您返回的是尚未设置的内容。让我们看看你的代码:
ccp.setOnCountryChangeListener(
new CountryCodePicker.OnCountryChangeListener() {
@Override
public void onCountrySelected() {
selected_country_code = ccp.getSelectedCountryCodeWithPlus();
}
});
代码似乎是说,当在微调器中选择国家时,您分配selected_country_code 的值。假设这是一个用户触发的动作,当你调用String abc = onCountryPickerClick();,你怎么能确定用户选择了什么?这就是问题所在。您不能确定用户已经选择了该选项并返回该值是不够的。
您可以通过多种方式解决此问题。例如,您可以继续传播回调:
public void onCountryPickerClick(OnCountryChangeListener listener){
ccp.setOnCountryChangeListener(listener);
}
// Anywhere you call this
onCountryPickerClick(new CountryCodePicker.OnCountryChangeListener() {
@Override
public void onCountrySelected() {
// Here do whatever you want with the selected country
}
});
上述方法与您现在的方法没有太大区别。还有其他选择。您可以使用 java observables,即:
class CountryCodeObservable extends Observable {
private String value;
public CountryCodeObservable(String value) {
this.value = value;
}
public void setCountryCode(String countryCode) {
value = countryCode;
setChanged();
notifyObservers(value);
}
}
public CountryCodeObservable onCountryPickerClick(){
CountryCodeObservable retValue = new CountryCodeObservable("");
ccp.setOnCountryChangeListener(
new CountryCodePicker.OnCountryChangeListener() {
@Override
public void onCountrySelected() {
retValue.setCountryCode(ccp.getSelectedCountryCodeWithPlus());
}
});
return retValue;
}
// Then when calling this method you can do something like:
CountryCodeObservable observable = onCountryPickerClick();
observable.addObserver((obj, arg) -> {
// arg is the value that changed. You'll probably need to cast it to
// a string
});
上面的例子允许你添加多个 observable。对于您的用例而言,这可能太多了,我只是认为它说明了另一种方法以及这种情况的异步性。
同样,还有更多的方法可以解决这个问题,关键是你不能简单地返回一个字符串并希望当用户选择任何东西时它会改变。