how to set google map fragment inside scroll view

后端 未结 8 973
北海茫月
北海茫月 2020-11-29 00:00

I want to set a Google map fragment inside vertical ScrollView, when I do the map does not zoom vertically, how can I override the touch event listener on

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 00:16

    This is the Kotlin version of Alok Nair's answer, I have to say that I am relatively new writing Kotlin code, any comment is appreciated.

    Custom SupportMapFragmet:

    class FocusMapFragment: SupportMapFragment() {
        var listener: OnTouchListener? = null
        lateinit var frameLayout: TouchableWrapper
    
        override fun onAttach(context: Context) {
            super.onAttach(context)
    
            frameLayout = TouchableWrapper(context)
            frameLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent))
        }
    
        override fun onCreateView(inflater: LayoutInflater, viewGroup: ViewGroup?, bundle: Bundle?): View? {
            val layout = super.onCreateView(inflater, viewGroup, bundle)
    
            val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            (layout as? ViewGroup)?.addView(frameLayout, params)
    
            return layout
        }
    
        interface OnTouchListener {
            fun onTouch()
        }
    
        inner class TouchableWrapper(context: Context): FrameLayout(context) {
            override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
                when (event?.action) {
                    MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP -> listener?.onTouch()
                }
                return super.dispatchTouchEvent(event)
            }
        }
    }
    

    Then change the fragment class in the xml:

    android:name="packagename.FocusMapFragment"
    

    And finally when you initialize the map:

    override fun onMapReady(googleMap: GoogleMap) {
        this.googleMap = googleMap
    
        (childFragmentManager.findFragmentById(R.id.mapView) as? FocusMapFragment)?.let {
            it.listener = object: FocusMapFragment.OnTouchListener {
                override fun onTouch() {
                    scrollView?.requestDisallowInterceptTouchEvent(true)
                }
            }
        }
        // ...
    }
    

    I tested this code in API 28 and 29, I couldn't find a Kotlin version anywhere so thought it could be useful for somebody.

提交回复
热议问题