【问题标题】:Spinner onItemSelected nedded only once, Android StudioSpinner onItemSelected 只需要一次,Android Studio
【发布时间】:2020-01-22 07:10:28
【问题描述】:

我正在尝试使用位于toolbar 中的spinner 来实现语言更改。现在我有spinner的以下代码:

initList();
Spinner spinnerCountries = findViewById(R.id.spinner_limba);
mAdapter = new SpinnerAdapterTara(Harta.this, mCountryList);
    spinnerCountries.setAdapter(mAdapter);
    spinnerCountries.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
        String clickedCountryName = clickedItem.getCountryName();
        if (clickedCountryName.equals("FR")){
            setLocale("fr");
            recreate();
        } else if (clickedCountryName.equals("EN")){
            setLocale("en");
            recreate();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});

initList(); 创建语言列表。这里的问题是关于onItemSelected,因为如果我选择fr 或en,setLocale("fr")/setLocale("en"); recreate(); 将持续运行,冻结我的应用程序。我需要一个解决方案来实现一次onItemSelected,比如onChangeListener 或其他东西。当 spinner 值更改时,应用程序应更改其语言。

编辑:我添加了setLocale():

private void setLocale(String limba){
    Locale locale = new Locale(limba);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale= locale;
    getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    SharedPreferences.Editor editor = getSharedPreferences("Setare limba", MODE_PRIVATE).edit();
    editor.putString("Limba mea", limba);
    editor.apply();
}

编辑:添加initList()

private void initList() {
    mCountryList = new ArrayList<>();
    mCountryList.add(new TaraITEM("RO", R.drawable.steag_ro));
    mCountryList.add(new TaraITEM("EN", R.drawable.steag_en));
    mCountryList.add(new TaraITEM("FR", R.drawable.steag_fr));
}

【问题讨论】:

标签: android


【解决方案1】:

使用static 变量来保存最后一个selection 并在重新创建activity 之前检查它给你带来onChangeListener 的味道

//Place inside Harta like global variable
static String lastCountryName = "";

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
    String clickedCountryName = clickedItem.getCountryName();

    // compare here before recreating
    if(!clickedCountryName.equals(lastCountryName)) {
        lastCountryName = clickedCountryName;

        if (clickedCountryName.equals("FR")){
            setLocale("fr");
            recreate();
        } else if (clickedCountryName.equals("EN")){
            setLocale("en");
            recreate();
        }
    }
}

【讨论】:

  • 像魅力一样工作。现在我需要找出为什么它不切换到EN,只切换到FR
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 2019-11-17
  • 2021-10-16
相关资源
最近更新 更多