1

I want to add a custom view programatically over an activity and place it in bottom-center of the activity.

So far, I am able to create a view, set its X and Y coordinates and add it to the root view but I am unable to center align the view.

Is there any way to achieve this?

I do not want to use the XML to achieve this as I want to add the view dynamically.

I have tried to search StackOverflow for this but cant get anything to work.

This is how I am adding the view.

        val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        mView = inflater.inflate(R.layout.view_popup_toast, null)
        mView?.findViewById<TextView>(R.id.popup_text)?.text = "Text"
        mView?.x = 500F
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        //This is not working
        //params.gravity = Gravity.CENTER_VERTICAL or Gravity.BOTTOM

        (window.decorView.rootView as ViewGroup).addView(mView, params)
dazzieta
  • 662
  • 4
  • 20
  • are you trying to achieve similar behavior of a toast? if so, what if your activity has other views, how are you showing the toast over it? – y.allam May 20 '20 at 19:41
  • Wrap the views of your XML layout in a FrameLayout so your `rootView` will be a FrameLayout. Then when creating this view programmatically, give it `FrameLayout.LayoutParams` so you can assign a gravity. – Tenfour04 May 20 '20 at 19:42
  • @y.allam Yes, I want something similar to Toast. But a toast is draw over the window directly and it makes it non intractable. I want this custom view to handle swipe gesture too. – dazzieta May 20 '20 at 19:52
  • @Tenfour04 Do you mean wrap my custom view's XML with FrameLayout or Activity's XML with FrameLayout? – dazzieta May 20 '20 at 19:53
  • 1
    The Activity's, so your view can overlay everything else. – Tenfour04 May 20 '20 at 20:11

1 Answers1

0

Try making the root view of your activity to be RelativeLayout, then when adding view_popup_toast use RelativeLayout.LayoutParams for it:

val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.CENTER_HORIZONTAL)
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)

(window.decorView.rootView as ViewGroup).addView(mView, params)
y.allam
  • 1,446
  • 13
  • 24
  • This approach will work, but it is not a reusable approach. What I am trying to achieve here is to make a reusable component, which could be added to any activity. So making root of activity is not feasible everywhere in app. – dazzieta May 20 '20 at 20:24
  • Yes you are right, so maybe a base activity here could solve this – y.allam May 20 '20 at 21:24