在我的应用中,我使用DrawerLayout
。当我切换到包含MapFragment
的{{1}}并返回时,Google地图会再次初始化。有没有办法阻止谷歌地图这样做?我正在使用Kotlin。我已经阅读了有关使用WeakReference到MapView的想法,但我不明白它在这种情况下可能会有什么帮助。
SupportMapFragment
答案 0 :(得分:1)
使用以下方法,您可以在“片段”关闭时执行任何操作:
@Override
public void onDestroy() {
super.onDestroy();
//Anything you wish to do
}
@Override
public void onDetach() {
super.onDetach();
//Anything you wish to do
}
答案 1 :(得分:0)
您必须通过此代码停止片段重新创建页面:
mViewPager.setOffscreenPageLimit(NumberOfYourPages);
答案 2 :(得分:0)
设置您以这种方式映射,
检查它是否已经存在
findFragmentById(R.id.map_new)
然后加载片段,否则使用已经加载。
childFragmentManager?.run {
findFragmentById(R.id.map)?.let {
val mapFragment = childFragmentManager.findFragmentById(R.id.map_new)
if (mapFragment is SupportMapFragment) {
mapFragment.getMapAsync(this@MapFragment)
}
}
}
编辑: -
这是活动oncreate: -
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_test)
supportFragmentManager.beginTransaction()
.replace(R.id.fragment, MapFragment.getInstance())
.addToBackStack("MapFragment")
.commit()
btnBlank.setOnClickListener {
val frag = supportFragmentManager.findFragmentById(R.id.fragment)
if(frag !is BlankFragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment, BlankFragment())
.addToBackStack("BlankFragment")
.commit()
}
}
btnMap.setOnClickListener {
supportFragmentManager.popBackStack("MapFragment", 0)
}
}
和MapFragment: -
class MapFragment : Fragment(), OnMapReadyCallback {
private lateinit var map: GoogleMap
companion object {
private val INSTANCE = MapFragment()
fun getInstance() = INSTANCE
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_map, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
childFragmentManager.run {
findFragmentById(R.id.map)?.let {
val mapFragment = childFragmentManager.findFragmentById(R.id.map)
if (mapFragment is SupportMapFragment) {
mapFragment.getMapAsync(this@MapFragment)
}
}
}
}
override fun onMapReady(p0: GoogleMap?) {
p0?.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(
p0.cameraPosition.target.latitude,
p0.cameraPosition.target.longitude
), 14f))
}
}