文本框值未根据微调器值的变化正确更新(我已经尝试了 stackoverflow 中的大多数方法)

Text box value not updating properly according to the change in spinner value (and i have tried most of the methods in stackoverflow)

MainActivity 中有一个微调器,fragment 中有 1 个文本框。我的任务是根据最近选择的微调器值更改文本框的值。我的代码运行良好,但文本框仅在 2 次滑动后才更改其状态。我不知道为什么会出现这种滞后现象。帮帮我(在投票之前请说出一些解决方案

这是我在主程序中的代码 activity

spinner = (Spinner)findViewById(R.id.spinner2);
final ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,array2);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter1);
spinner.invalidate();

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //dataAdapter1.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(),"well",Toast.LENGTH_LONG).show();
        String pos = (String) spinner.getSelectedItem();
        SharedPreferences sharedPref = getSharedPreferences("Mode", Activity.MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = sharedPref.edit();
        prefEditor.putString("userChoicemode", pos);
        prefEditor.commit();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

我的片段代码:

final TextView modeselect = (TextView) view.findViewById(R.id.pass);

final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("Mode", Activity.MODE_PRIVATE);
String get = sharedPref.getString("userChoicemode",selected);

modeselect.setText("" + get);

在你的片段中

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    try {
        if (isVisibleToUser) {
            final TextView modeselect = (TextView) view.findViewById(R.id.pass);

final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("Mode", Activity.MODE_PRIVATE);
String get = sharedPref.getString("userChoicemode",selected);

modeselect.setText("" + get);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    super.setUserVisibleHint(isVisibleToUser);
}

只需将此覆盖方法添加到您的片段中,并在此方法中将所选微调项的值放入片段的文本视图中。你的膨胀视图应该全局声明