Android how to stop refreshing Fragments on tab change

前端 未结 7 1353
小蘑菇
小蘑菇 2020-12-12 22:09

I have the following code :

MainActivity.java

package com.erc.library;

import java.io.BufferedInputStream;
import java.io.File;
imp         


        
7条回答
  •  执念已碎
    2020-12-12 23:03

    In my case above suggestion does not work.

    To restrict recreation of fragment, what i did:

    In onCreateView you can store inflated view in a global variable and initialize it only if it is null, like in this code:

        var root:View?=null
        var apiDataReceived=false
     override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        if (root==null)
            root=inflater!!.inflate(R.layout.fragment_layout, container, false)
        return root
    }
    

    Now if you are parsing some data and fill it into RecyclerView or any other View

    1. Make a global variable like in above code apiDataReceived

    2. Set it to true if you successfully parsed data.

    3. Before apiCalls place a condition like this:

      if (!apiDataReceived) { apiCalls() }

    So if apiCalls() would be called only if data is not parsed.

    Do your http calls and parsing or any other thing in method which called after onCreateView like onStart

    The above code is in kotlin, If you are facing any issue, let me know in comments.

提交回复
热议问题