我有一个下拉列表,我在上面设置了一些值,并显示,默认情况下,最后一个值用户保存从共享pref。它工作得很好。问题是当我启动活动时,将这个保存的用户值放在select上,作为默认值,它正在调用 setOnItemSelectedListener
向用户敬酒。我不想在setonitemselectedlistener中运行块代码,只是在用户更改下拉值时。你知道怎么解决吗?
String defaultValue = pref02.getString("fonte", "Normal");
String[] items = new String[]{"Normal", "10", "12", "14", "16", "18", "20", "24", "28", "30"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
int spinnerPosition = adapter.getPosition(defaultValue);
dropdown.setSelection(spinnerPosition); //select the atual saved value.
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SharedPreferences pref2 = getApplicationContext().getSharedPreferences("pref02", MODE_PRIVATE);
SharedPreferences.Editor editor = pref2.edit();
String drop = dropdown.getSelectedItem().toString();
editor.putString("fonte", drop);
editor.apply();
Toast.makeText(Config.this, "Saved :)", Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
1条答案
按热度按时间s4chpxco1#
解决方案:使用下面的代码(您可以查看注解行以查看指南)