📌  相关文章
📜  如何使用 Jetpack Compose 在 Android 中选择文本?

📅  最后修改于: 2022-05-13 01:55:17.197000             🧑  作者: Mango

如何使用 Jetpack Compose 在 Android 中选择文本?

默认情况下,可组合文本是不可选择的,这意味着用户无法从您的应用程序复制文本,并且要启用文本选择,您需要将文本元素包装到选择容器中。在本文中,我们将使用 Android 的 Jetpack Compose 来创建这些芯片。下面给出了一个示例图像,以了解我们将要构建的内容。请注意,我们将使用 Kotlin 语言来实现这个项目。

分步实施

第 1 步:创建一个新项目

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

步骤 2:使用 MainActivity.kt 文件



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

Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.selection.DisableSelection
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetpack_playground.ui.theme.Jetpack_playgroundTheme
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Jetpack_playgroundTheme {
                // A surface container using the 
                  // 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    // call the CustomSelectableText() function
                    // it is defined below
                    Column {
                        CustomSelectableText()
                    }
                }
            }
        }
    }
}
  
// create a composable function
// for the selectable text.
// Wrap the text inside SelectionContainer()
// in order to make it selectable
@Composable
fun CustomSelectableText() {
    SelectionContainer() {
        Column() {
            Text(
                text = "Welcome to Geeks for Geeks,A Computer Science portal for geeks." +
                        "It contains well written, well thought and well explained computer " +
                        "science and programming articles, quizzes and ...",
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(start = 10.dp, top = 20.dp)
                    .fillMaxWidth()
            )
        }
    }
}
  
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    Jetpack_playgroundTheme {
        CustomSelectableText()
    }
}


输出:

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