我正在尝试使用设置为 View.GONE 的 LinearLayout 制作一些下拉菜单。单击按钮时,可见性将更改为可见,并且内容将垂直显示在按钮下方。我希望发生的是垂直视图将绘制在按钮下方的任何视图上。现在发生的是按钮下方的视图并被按下。
有没有办法实现这个目标?
要实现在按钮下方的任何视图上绘制垂直视图的所需行为,您可以在 Kotlin 中使用
PopupWindow
。这是一个简单的例子:
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)
}
}
}
}