I have only one activity and all navigation is solved through fragments. If I open the fragment and come back, the fragment will be still in memory and memory will be growing.
What am I doing wrong? Do I have to manually remove listeners? In the onDestroy
method, getView
is already null.
How I add fragments:
fun replaceFragment(
fragmentManager: FragmentManager?,
fragment: Fragment?,
frameId: Int,
tag: String?
) {
if (fragmentManager != null && fragment != null) {
val previousFragment = fragmentManager.findFragmentById(frameId)
if (fragment != previousFragment) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(frameId, fragment, tag)
transaction.addToBackStack(tag)
transaction.commitAllowingStateLoss()
}
}
}
Fragment close by the back button:
EDIT: How I create Fragment
companion object {
fun create(number: Long): ManageUnitFragment {
val fragment = ManageUnitFragment()
val params = Bundle()
params.putLong(Keys.Number, number)
fragment.arguments = params
return fragment
}
}
How I set Listeners (on buttons)
import kotlinx.android.synthetic.main.myFragment.*
vMyButton.setOnClickListener {
myAction()
}
EDIT If I remove this line vButtonClose.setOnClickListener...
, the ManageUnitFragments will no longer be in the heap dump.
ManageUnitFragment:
import kotlinx.android.synthetic.main.fragment_manage_unit.*
class ManageUnitFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_manage_unit, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
vButtonClose.setOnClickListener {
activity?.onBackPressed()
}
}
companion object {
fun create(unitNumber: Long, wagonWagonUnit: WagonUnit): ManageUnitFragment {
val fragment = ManageUnitFragment()
return fragment
}
}
}
Have you tried to add 'many' fragments? Do you actually get OutOfMemoryException
?
Maybe they just remain in memory until more of it is needed. Then they will be garbage collected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.