简体   繁体   中英

Does Material Components provide edit text dialog when I use Jetpack Compose?

I need a edit text dialog when I use Jetpack Compose in my project.

The Code A is from the article .

Q1: I don't know if Code A can use in Jetpack Compose, could you tell me?

I was told that Dialogs are available in the Material library for Jetpack Compose

It seems that Material library only provide Alert dialog, Simple dialog and Confirmation dialog.

Q2: Does Material Components provide edit text dialog when I use Jetpack Compose?

Code A

AlertDialog.Builder alert = new AlertDialog.Builder(this); 

final EditText edittext = new EditText(ActivityContext);
alert.setMessage("Enter Your Message");
alert.setTitle("Enter Your Title");

alert.setView(edittext);

alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //What ever you want to do with the value
        Editable YouEditTextValue = edittext.getText();
        //OR
        String YouEditTextValue = edittext.getText().toString();
    }
});

alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // what ever you want to do with No option.
    }
});

alert.show();

AlertDialog implementation from Jetpack Compose allows you to add title, buttons and text as a content.

If you want to add an EditText (or, more preciesly, TextField) instead of just text, you may create your own layout for dialog like this:

@Composable
fun MyAlertDialog(
    title: @Composable () -> Unit,
    content: @Composable () -> Unit,
    dismissButton: @Composable () -> Unit,
    confirmButton: @Composable () -> Unit,
    onDismiss: () -> Unit,
) {
    Dialog(onDismiss) {
        Surface(shape = MaterialTheme.shapes.medium) {
            Column {
                Column(Modifier.padding(24.dp)) {
                    title.invoke()
                    Spacer(Modifier.size(16.dp))
                    content.invoke()
                }
                Spacer(Modifier.size(4.dp))
                Row(
                    Modifier.padding(8.dp).fillMaxWidth(),
                    Arrangement.spacedBy(8.dp, Alignment.End),
                ) {
                    dismissButton.invoke()
                    confirmButton.invoke()
                }
            }
        }
    }
}

If you call this composable function with OutlinedTextField as a content, result will look like this:

截屏

You can see full working demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM