How do I create an Android Spinner as a popup?

后端 未结 12 1764
梦如初夏
梦如初夏 2020-12-02 09:20

I want to bring up a spinner dialog when the user taps a menu item to allow the user to select an item.

Do I need a separate dialog for this or can I use Spinner dir

12条回答
  •  粉色の甜心
    2020-12-02 09:48

    Here is a Kotlin version based on the accepted answer.

    I'm using this dialog from an adapter, every time a button is clicked.

    yourButton.setOnClickListener {
        showDialog(it /*here I pass additional arguments*/)
    }
    

    In order to prevent double clicks I immediately disable the button, and re-enable after the action is executed / cancelled.

    private fun showDialog(view: View /*additional parameters*/) {
        view.isEnabled = false
    
        val builder = AlertDialog.Builder(context)
        builder.setTitle(R.string.your_dialog_title)
    
        val options = arrayOf("Option A", "Option B")
    
        builder.setItems(options) { dialog, which ->
            dialog.dismiss()
    
            when (which) {
                /* execute here your actions */
                0 -> context.toast("Selected option A")
                1 -> context.toast("Selected option B")
            }
    
            view.isEnabled = true
        }
    
        builder.setOnCancelListener {
            view.isEnabled = true
        }
    
        builder.show()
    }
    

    You can use this instead of a context variable if you are using it from an Activity.

提交回复
热议问题