由于片段没有onRestore状态,因此我试图在重新启动应用程序后还原微调器对象。那么如何实现以下代码来从微调器中还原所选项目?
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
spinnerItem = savedInstanceState
}
}
答案 0 :(得分:0)
也许这会有所帮助,以前的评论将被删除,所以我发布了一个新评论,但回复不同
public class MyFragment extends Fragment{
private String[] choices = new String[]{"one", "two", "three"};
// Initial position
private int spinnerPosition = 0;
private static final String SPINNER_ITEM_POSITION = "whatever_label_fits_you";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.my_fragment, container, false);
// This part is here to simulate a real Spinner since your example didn't include one
final AppCompatSpinner spinner = view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, choices);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
spinnerPosition = i;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
if (savedInstanceState != null)
spinnerPosition = savedInstanceState.getInt(SPINNER_ITEM_POSITION);
spinner.setSelection(spinnerPosition);
return view;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState)
{
// Save current position to bundle so you can retrieve it in onCreateView
outState.putInt(SPINNER_ITEM_POSITION, spinnerPosition);
super.onSaveInstanceState(outState);
}}
如果仍然无法解决问题,您可以随时检查Once for all, how to correctly save instance state of Fragments in back stack?,该答案回答了如何将实例保存在片段中的问题。 为此,请确保仅在onCreate方法中的savedInstanceState为null时才创建Fragment,因为否则,由于始终创建新的片段,您将丢失所有保存的数据。