无法读取在微调器Android中选择的国家/地区代码

问题描述

我正在开发一个应用程序,其中用户必须选择国家/地区代码,为此目的,我成功地创建了一个微调框,如以下链接所示:
Creating a spinner for choosing country code 但是我在读取微调器中选择的值时遇到问题。

app.listen(process.env.PORT,'0.0.0.0');

解决方法

回调不同步。不幸的是,您不能简单地做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
});

以上示例使您可以添加多个可观察项。对于您的用例来说可能太多了,我只是认为它说明了另一种方法,并且还说明了这种情况的异步性。

同样,还有更多的方法可以解决此问题,关键是您不能简单地返回一个字符串并希望它在用户选择任何内容时进行更改。

,

调用String abc = onCountryPickerClick();时,selected_country_code值将分配给abc

当您的CountryCodePicker.OnCountryChangeListener的{​​{1}}方法被调用时,onCountrySelected()的值将分配给ccp.getSelectedCountryCodeWithPlus();。由于selected_country_code是不可变的,因此更改String的值不会更改selected_country_code的值,也不会调用abc

可能的解决方案之一是更改您的return selected_country_code;匿名实现,以将选定的国家/地区值分配给CountryCodePicker.OnCountryChangeListener,例如

abc