从后台恢复后保留ui状态

时间:2013-06-29 15:15:27

标签: android android-fragments back-stack

我在使用后台堆栈时有关于保留我的ui状态的问题。

方案
两个片段与setRetainInstance(true)一起使用;并且他们的ui是在onActivityCreated()中创建的。一个片段有一个GridView,当通过backstack返回时,它应该保留其滚动位置,更改为另一个App等。

问题:
我有一个带有几个项目的GridView,如果我按下主页并返回我的应用程序,它会保留滚动位置 但是如果我滚动,转到另一个片段并通过后退按钮返回,则重新创建ui(不保留scrollpos)。

我需要做什么,在使用backstack时保留ui状态而不手动保存和恢复每个状态?

更新

我不认为我的代码在这里很重要,因为我只是不知道原理。我的代码已经可以正常运行,只有片段不起作用,因为我通过backstack回到另一个活动。如果我按下主页然后再次启动我的应用程序,所有内容都会按预期保留,并使用此片段。

MainFragment:

公共类ThumbnailFragment extends Fragment实现了IView {

GlobalModel model;
ThumbnailController controller;


final ApplicationDataHolder appDataHolder = new ApplicationDataHolder().getInstance();

PreferencesProvider preferences;
Button datePicker;
Spinner newspaperEditionSelector;
TextView newspaperEditionViewer;
GridView thumbnailView;
ImageSwitcher nothingLoaded;

int newspaperEditionPosition = -1;
String newspaperDate = null;
protected Adapter initializedAdapter = null;

@Override
public void updateView() {
    newspaperEditionSelector = (Spinner) getActivity().findViewById(R.id.newspaperEditionSelector);
    newspaperEditionViewer = (TextView) getActivity().findViewById(R.id.newspaperEditionViewer);
    thumbnailView = (GridView) getActivity().findViewById(R.id.thumbnailFragment_thumbnailList);
    datePicker = (Button) getActivity().findViewById(R.id.choosenDate);
    nothingLoaded = (ImageSwitcher) getActivity().findViewById(R.id.nothingLoaded);

    if (newspaperEditionSelector == null || newspaperEditionViewer == null || thumbnailView == null || datePicker == null || nothingLoaded == null)
        return;

    if (model.getSubscriptions() == null || model.getSubscriptions().size() < 1) {
        Bundle args = new Bundle();
        args.putBoolean("promptForLoginData", true);
        MainActivity.showFragment(getActivity(), getFragmentManager(), SettingsFragment.class.getName(), args, true);
    } else {
        if (model.getSubscriptions().size() > 1) {
            // Use spinner for user to select desired edition
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, model.getSubscriptions());
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            newspaperEditionSelector.setAdapter(dataAdapter);
            newspaperEditionSelector.setSelection(newspaperEditionPosition);
            this.newspaperEditionSelector.setVisibility(View.VISIBLE);
            this.newspaperEditionViewer.setVisibility(View.GONE);
        } else {
            // because only one edition for user exists use textview instead
            // of spinner
            this.newspaperEditionViewer.setText(model.getSubscriptions().get(0));
            this.newspaperEditionViewer.setVisibility(View.VISIBLE);
            this.newspaperEditionSelector.setVisibility(View.GONE);
            preferences.setIntegerPreference("ChoosenThumbnailNewspaperEdition", 0);
        }

        // Create on item choose listener
        newspaperEditionSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
                if (initializedAdapter != parent.getAdapter()) {
                    initializedAdapter = parent.getAdapter();
                    return;
                } else {
                    newspaperEditionPosition = (int) parent.getSelectedItemId();
                    preferences.setIntegerPreference("ChoosenThumbnailNewspaperEdition", newspaperEditionPosition);
                    controller.loadNewspaper(newspaperDate, model.getSubscriptions().get(newspaperEditionPosition));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        // Prepare date picker ui
        datePicker.setText(newspaperDate);
        datePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datePicker");
            }
        });

        datePicker.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                //controller.loadNewspaper(newspaperDate, model.getSubscriptions().get(newspaperEditionPosition));
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

        String title = "";
        if (model.getThumbnailsAdapter() == null) {
            nothingLoaded.setVisibility(View.VISIBLE);
            title += "...";
        } else {
            nothingLoaded.setVisibility(View.GONE);
            title += "Zeitung - " + model.getSubscriptions().get(newspaperEditionPosition) + (newspaperDate != null ? " von " + newspaperDate : "");
        }
        getActivity().getActionBar().setTitle(title);
    }
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);

        preferences = new PreferencesProvider(getActivity());
        this.newspaperEditionPosition = preferences.getIntegerPreference("ChoosenThumbnailNewspaperEdition");
        this.newspaperDate = (preferences.getStringPreference("ChoosenThumbnailNewspaperDate").equals("") ? "Aktuell" : preferences.getStringPreference("ChoosenThumbnailNewspaperDate"));

        model = new GlobalModel().getInstance();
        model.init(getActivity().getApplicationContext());
        model.registerView(new WeakReference<IView>(this));
        controller = new ThumbnailController(model, this.getActivity());
        controller.loadSubscriptions();

        if (model.getSubscriptions() != null)
            controller.loadNewspaper(newspaperDate, model.getSubscriptions().get(newspaperEditionPosition));


            thumbnailView.setAdapter(model.getThumbnailsAdapter());
            thumbnailView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // Change fragment to pageview
                    Bundle args = new Bundle();
                    args.putString("newspaperEdition", model.getSubscriptions().get(newspaperEditionPosition));
                    args.putString("newspaperDate", newspaperDate);
                    args.putInt("newspaperPagePosition", position + 1);
                    args.putInt("newspaperPagesCount", parent.getAdapter().getCount());
                    MainActivity.showFragment(getActivity(), getFragmentManager(), PageFragment.class.getName(), args, true);
                }
            });
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.fragment_thumbnail, container, false);
}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Clear and replace menu in actionbar and hide listbox
    final ActionBar actionBar = getActivity().getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(R.string.title_thumbnail_fragment);
    actionBar.setDisplayHomeAsUpEnabled(false);
    menu.clear();
    inflater.inflate(R.menu.thumbnail_fragment_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_goto_search:
            MainActivity.showFragment(getActivity(), getFragmentManager(), SearchFragment.class.getName(), null, true);
            break;
        case R.id.menu_export_pdf:
            NewspaperDownloader task = new NewspaperDownloader(getActivity(), model.getSubscriptions().get(newspaperEditionPosition), this.newspaperDate, -1);
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            break;
        case R.id.menu_settings:
            MainActivity.showFragment(getActivity(), getFragmentManager(), SettingsFragment.class.getName(), null, true);
            break;
        case R.id.menu_exit:
            getActivity().finish();
            System.exit(0);
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return false;
}


}

0 个答案:

没有答案