📌  相关文章
📜  使用Jetpack Compose在Android中编辑文本

📅  最后修改于: 2021-05-10 14:35:12             🧑  作者: Mango

EditText是最重要的小部件之一,在大多数应用程序中都可以看到。该小部件通常用于从用户那里获取数据。用户可以使用此小部件直接与应用通信。该小部件用于以数字,文本或任何其他文本的形式从用户获取数据。在本文中,我们将介绍使用Jetpack Compose在Android中实现EditText小部件的过程。

EditText小部件的属性

Attributes 

Description

value  value is use to get the entered value from the user in the text field.
placeholder

if the text field is empty we are displaying a hint to the user what he 

has to enter in the text field. 

keyboardOptions

keyboardOptions is used to add capitalization in the data which is entered by 

user in text field, we can also specify auto correction option in this. We can specify 

the type of keyboard which we have to display such as (phone, text) and to display

actions which can be performed from the keyboard itself. 

textStyle to add styling to the text entered by user. It is used to add font family, font size and styling to our text. 
maxLines to add maximum lines for our text input field. 
activeColor

active color is use to when user has click on edit text or the text field is focused and 

entering some data in the text field. 

singleLine In this we have to specify a boolean value to avoid moving user input into multiple lines. 
inactiveColor Inactive color is specified when user is not being focused on our Text Input Field. 
backgroundColor to specify background color for our text input field.
leadingIcon

This method is use to add leading icon to our text input field. With this method

we can also specify color(tint) for our icon.

trailingIcon

This method is use to add trailing icon to our text input field. With this method 

we can also specify color(tint) for our icon.

分步实施

步骤1:创建一个新项目

要在Android Studio Canary版本中创建新项目,请参阅如何使用Jetpack Compose在Android Studio Canary版本中创建新项目。

步骤2:在MainActivity.kt文件中添加EditText

导航到应用程序> Java >您的应用程序的程序包名称,然后打开MainActivity.kt文件。在该文件内,添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Kotlin
package com.example.gfgapp
  
import android.graphics.drawable.shapes.Shape
import android.media.Image
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Phone
import androidx.compose.runtime.*
import androidx.compose.runtime.savedinstancestate.savedInstanceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.gfgapp.ui.GFGAppTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.ContextAmbient
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.*
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            GFGAppTheme {
                // A surface container using the 
                  // 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    // at below line we are calling 
                      // our function for text field.
                    TxtField();
                }
            }
        }
    }
}
  
@Composable
fun TxtField() {
    // we are creating a variable for
    // getting a value of our text field.
    val inputvalue = remember { mutableStateOf(TextFieldValue()) }
    Column(
            // we are using column to align our 
            // imageview to center of the screen.
            modifier = Modifier.fillMaxWidth().fillMaxHeight(),
              
            // below line is used for specifying
            // vertical arrangement.
            verticalArrangement = Arrangement.Center,
              
            // below line is used for specifying 
            // horizontal arrangement.
            horizontalAlignment = Alignment.CenterHorizontally,
    )
    {
        TextField(
                // below line is used to get 
                // value of text field,
                value = inputvalue.value,
                  
                // below line is used to get value in text field
                // on value change in text field.
                onValueChange = { inputvalue.value = it },
                  
                // below line is used to add placeholder 
                // for our text field.
                placeholder = { Text(text = "Enter user name") },
                  
                // modifier is use to add padding 
                // to our text field.
                modifier = Modifier.padding(all = 16.dp).fillMaxWidth(),
                  
                // keyboard options is used to modify 
                // the keyboard for text field.
                keyboardOptions = KeyboardOptions(
                        // below line is use for capitalization 
                        // inside our text field.
                        capitalization = KeyboardCapitalization.None,
                          
                        // below line is to enable auto 
                        // correct in our keyboard.
                        autoCorrect = true,
                          
                        // below line is used to specify our 
                        // type of keyboard such as text, number, phone.
                        keyboardType = KeyboardType.Text,
                ),
  
                // below line is use to specify 
                // styling for our text field value.
                textStyle = TextStyle(color = Color.Black,
                        // below line is used to add font 
                        // size for our text field
                        fontSize = TextUnit.Companion.Sp(value = 15),
                          
                        // below line is use to change font family.
                        fontFamily = FontFamily.SansSerif),
                  
                // below line is use to give
                // max lines for our text field.
                maxLines = 2,
                  
                // active color is use to change 
                // color when text field is focused.
                activeColor = colorResource(id = R.color.purple_200),
                  
                // single line boolean is use to avoid 
                // textfield entering in multiple lines.
                singleLine = true,
                  
                // inactive color is use to change 
                // color when text field is not focused.
                inactiveColor = Color.Gray,
                  
                // below line is use to specify background
                // color for our text field.
                backgroundColor = Color.LightGray,
                  
                // leading icon is use to add icon 
                // at the start of text field.
                leadingIcon = {
                    // In this method we are specifying 
                    // our leading icon and its color.
                    Icon(Icons.Filled.AccountCircle, tint = colorResource(id = R.color.purple_200))
                },
                // trailing icons is use to add 
                // icon to the end of tet field.
                trailingIcon = {
                    Icon(Icons.Filled.Info, tint = colorResource(id = R.color.purple_200))
                },
                )
    }
}
  
// @Preview function is use to see preview
// for our composable function in preview section
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    GFGAppTheme {
        TxtField()
    }
}


输出:

使用Jetpack Compose在Android中编辑文本

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处前往由我们的专家精心策划的指南,以使您立即做好行业准备!