AlertDialog

Cómo crear un AlertDialog a medida

How to Create a Custom AlertDialog in Android?

Crear el fichero custom_layout.xml

res/layout/custom_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout ç
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"> 

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" /> 
</LinearLayout>

Añadir un botón en activity_main.xml y asociarle el método showAlertDialogButtonClicked

res/layout/showAlertDialogButtonClicked

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity"> 

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showAlertDialogButtonClicked"
        android:text="Show Dialog" /> 
</LinearLayout>

Mostrar el AlertDialog en el MainActivity

MainActivity.kt

import android.content.DialogInterface 
import android.os.Bundle 
import android.view.View 
import android.widget.EditText 
import android.widget.Toast 
import androidx.appcompat.app.AlertDialog 
import androidx.appcompat.app.AppCompatActivity 

class MainActivity : AppCompatActivity() { 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContentView(R.layout.activity_main) 
    } 

    fun showAlertDialogButtonClicked() { 
        // Create an alert builder 
        val builder = AlertDialog.Builder(this) 
        builder.setTitle("Name") 

        // set the custom layout 
        val customLayout: View = layoutInflater.inflate(R.layout.custom_layout, null) 
        builder.setView(customLayout) 

        // add a button 
        builder.setPositiveButton("OK") { dialog: DialogInterface?, which: Int -> 
            // send data from the AlertDialog to the Activity 
            val editText = customLayout.findViewById<EditText>(R.id.editText) 
            sendDialogDataToActivity(editText.text.toString()) 
        } 
        // create and show the alert dialog 
        val dialog = builder.create() 
        dialog.show() 
    } 

    // Do something with the data coming from the AlertDialog 
    private fun sendDialogDataToActivity(data: String) { 
        Toast.makeText(this, data, Toast.LENGTH_SHORT).show() 
    } 
}

Más información:

How to Create an Alert Dialog Box in Android?

Dialogs

Deja una respuesta