How to make the Fragment not be destroyed

Viewed 28

I am trying to write applications for andorida from a fragment and a webview where in one application I have 4 cards and each card has a different stone. The problem is that when I switch from card 1 to card 4, everything that I did on card 1 is deleted and the reverse restarts and the same from 4 to 1. Is it possible for the Fragment not to be destroyed and be in the background nom stop working?

fragment1

public class Fragment1 extends CustomFragment {

WebView webView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment1_layout, container, false);
    
    WebView view = (WebView) rootView.findViewById(R.id.webView1);
    


    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setAppCacheEnabled(true);
    view.getSettings().setDatabaseEnabled(true);
    view.getSettings().setDomStorageEnabled(true);
    view.getSettings().setSupportZoom(true);
    view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    view.getSettings().setBuiltInZoomControls(true);
    //view.setInitialScale(1);
    view.setPadding(0, 0, 0, 0);
    view.getSettings().setDisplayZoomControls(true);
    view.getSettings().setLoadWithOverviewMode(true);
    view.getSettings().setUseWideViewPort(true);
    view.getSettings().setAllowContentAccess(true);
    view.getSettings().setAllowFileAccess(true);
    view.getSettings().setDomStorageEnabled(true);

    view.getSettings().setGeolocationEnabled(true);
    view.setWebViewClient(new WebViewClient(){
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    });

    view.loadUrl("http://mdm.aq.local:8181/strona.html");
    

    view.setWebChromeClient(new WebChromeClient() {

    });

    return rootView;

}}
1 Answers

In Fragment1's case, you can save the state of the WebView like this:

// Saving...
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        webView.saveState(outState)
    }

// Retrieving...
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        if (savedInstanceState != null) {
            webView.restoreState(savedInstanceState)
        }
    }

Also, it is advisable to use a ViewModel when saving data obtained from external data source such as a server or local repository.

For more information with regards to saving Fragment's state read this

Related