How to make OutlinedTextField Single Line in Android Jetpack Compose

By Mohammed Rashid •  November 22nd, 2022 • 

OutlinedTextField in Jetpack Compose is multiline by default. As a mobile app developer, you may want to set a maximum number of lines for TextField. Let’s check how to do the same.

TextField composable has many useful parameters and singleLine is one among them. Just make singleLine true and you are ready to go.

@Composable
fun TextFieldExample() {
    var value by remember { mutableStateOf("") }
    OutlinedTextField(
        value = value,
        singleLine = true,
        onValueChange = {
            value = it
        },
        label = { Text("Enter text") },
        modifier = Modifier.padding(20.dp)
    )
}

See the following output.

outlinedtextfield single line jetpack compose

The same way you can also make the TextField single line. Following is the complete of this example for reference.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    TextFieldExample()
                }
            }
        }
    }
}

@Composable
fun TextFieldExample() {
    var value by remember { mutableStateOf("") }
    OutlinedTextField(
        value = value,
        singleLine = true,
        onValueChange = {
            value = it
        },
        label = { Text("Enter text") },
        modifier = Modifier.padding(20.dp)
    )
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        TextFieldExample()
    }
}

I hope you liked this Jetpack Compose OutlinedTextField single line tutorial.

Keep Reading