Search code examples
javaandroiddropdown

Expand a views height and have it draw over a lower View instead of pushing it down?


I'm trying to make some dropdown menus using a LinearLayout that's set to View.GONE. when a button is clicked the visibility will change to Visible and the contents will be shown vertically below the button. What'd I'd like to have happen is the vertical View will be drawn over any views that are below the button. What happens now is the Views below the button and pushed down.

Is there a way to achieve this?


Solution

  • To achieve the desired behavior where the vertical view is drawn over any views below the button, you can use a PopupWindow in Kotlin. Here's a simple example:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val button = findViewById<Button>(R.id.button)
            val popupView: View = LayoutInflater.from(this).inflate(R.layout.popup_layout, null)
    
            val popupWindow = PopupWindow(
                popupView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true
            )
    
            button.setOnClickListener {
                if (popupWindow.isShowing) {
                    popupWindow.dismiss()
                } else {
                    // Show popup at the bottom of the button
                    popupWindow.showAsDropDown(button)
                }
            }
        }
    }