M
M
Matvey Filatov2016-05-03 17:17:41
Android
Matvey Filatov, 2016-05-03 17:17:41

Why is a fragment added every time the application is minimized/maximized?

There is a Fragment that implements the LoaderManager.LoaderCallbacks<> interface. In the onLoadFinished method, a TextView is added to the Fragment. If you collapse the application, and then expand it, the same TextView will be added. Thus, if we collapse and expand the application, we will get a lot of TetxView, but only one is needed. How to achieve the desired result?

public class SelectedListFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<SomeList>> {

    private LinearLayout linearLayout;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(R.id.some_list_loader, Bundle.EMPTY, this);

        linearLayout = (LinearLayout) getActivity().findViewById(R.id.selectedListFragment);
    }

    @Override
    public Loader<List<SomeList>> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case R.id.some_list_loader:
                return new SomeListLoader(getContext());
            default:
                return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<List<SomeList>> loader, List<SomeList> data) {
        int loaderId = loader.getId();
        if (R.id.some_list_loader == loaderId) {
            if (linearLayout != null) {
                linearLayout.setBackgroundColor(Color.BLUE);
                TextView textView = new TextView(getContext());
                textView.setText("Это текст-вью добавлено из кода, после загрузки данных !");
                linearLayout.addView(textView);
            }

        }
    }

    @Override
    public void onLoaderReset(Loader<List<SomeList>> loader) {
        Log.i(Tags.INFO, "loader: " + loader.getId() + "was reset !" );
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question