Search code examples
androidandroid-layoutkotlin-android-extensionskotlin-extension

Extend ViewGroup as a fragment wrapper


I am extending a RelativeLayout to make a fragment decorator.

Like this:

<br.com.simplepass.mapfragmentwrapper.MapFragmentWrapper
        android:id="@+id/map_wrapper"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/main_fragment_map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.MapFragment"/>

</br.com.simplepass.mapfragmentwrapper.MapFragmentWrapper>

Well, I would like to add some images in the RelativeLayout so it always get on top of the fragment, so I did this:

class MapFragmentWrapper : RelativeLayout {

    var mMarkImageView : ImageView? = null
    var mShadowView : View? = null

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context)
    }

    @TargetApi(23)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        init(context)
    }

    private fun init(context: Context) {

        val params = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

        mMarkImageView = ImageView(context)
        mMarkImageView?.setImageResource(R.drawable.ic_marker_centered)

        mShadowView = View(context)
        mShadowView?.setBackgroundResource(R.drawable.map_pin_shadow)

        addView(mMarkImageView, params)
        addView(mShadowView, params)


    }
[some more code here...]

}

But, when my activity starts, the fragment gets on top of my added views (mMarkImageView and mShadowView)... and that's exactly the opposite of what a want.

So how do I programmatically put the views at the last position in viewgroups?

Any help is appreciated!


Solution

  • So I found the answer:

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
            super.onLayout(changed, l, t, r, b)
    
            removeView(mMarkImageView)
            removeView(mShadowView)
            addView(mMarkImageView, -1 , params)
            addView(mShadowView, -1, params)
        }
    

    doing this I put the layouts at the end of the viewgroup