📌  相关文章
📜  使用 Jetpack Compose 在 Android 中的特定文本范围内添加超链接

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

使用 Jetpack Compose 在 Android 中的特定文本范围内添加超链接

在 Android 中,TextView 用于在屏幕上显示 Activity 内的文本。同样,在 Jetpack Compose 中,Text 元素用于在活动屏幕上显示文本。默认情况下,Text 无法在文本周围创建超链接,因此,我们使用 Annonated String 创建超链接并使用 Clickable Text 显示它。

因此,在本文中,我们将向您展示如何使用 Jetpack Compose 在 Android 中的特定文本范围内创建超链接。 IDE 准备就绪后,请按照以下步骤操作。

分步实施

第 1 步:在 Android Studio 中创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。选择模板时,选择Empty Compose Activity 。如果您没有找到此模板,请尝试将 Android Studio 升级到最新版本。我们在Kotlin中演示了该应用程序,因此请确保在创建新项目时选择 Kotlin 作为主要语言。

第 2 步:在 AndroidManifest.xml 文件中添加 INTERNET 权限

XML


  
    
  
    
        
            
                
  
                
            
        
    
  


Kotlin
package com.geeksforgeeks.jctextspanhyperlink
  
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // Calling the composable function
            // to display element and its contents
            MainContent()
        }
    }
}
  
// Creating a composable 
// function to display Top Bar
@Composable
fun MainContent() {
    Scaffold(
        topBar = { TopAppBar(title = { Text("GFG | Text Span Hyperlink", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
        content = { MyContent() }
    )
}
  
// Creating a composable function 
// to create a Clickable Text
// Calling this function as content
// in the above function
@Composable
fun MyContent(){
  
    // Creating an annonated string
    val mAnnotatedLinkString = buildAnnotatedString {
  
        // creating a string to display in the Text
        val mStr = "Click this link to go to web site"
        
        // word and span to be hyperlinked
        val mStartIndex = mStr.indexOf("link")
        val mEndIndex = mStartIndex + 4
        
        append(mStr)
        addStyle(
            style = SpanStyle(
                color = Color.Blue,
                textDecoration = TextDecoration.Underline
            ), start = mStartIndex, end = mEndIndex
        )
  
        // attach a string annotation that 
        // stores a URL to the text "link"
        addStringAnnotation(
            tag = "URL",
            annotation = "https://www.geeksforgeeks.org",
            start = mStartIndex,
            end = mEndIndex
        )
  
    }
  
    // UriHandler parse and opens URI inside 
    // AnnotatedString Item in Browse
    val mUriHandler = LocalUriHandler.current
  
    Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
  
        // ???? Clickable text returns position of text 
        // that is clicked in onClick callback
        ClickableText(
            text = mAnnotatedLinkString,
            onClick = {
                mAnnotatedLinkString
                    .getStringAnnotations("URL", it, it)
                    .firstOrNull()?.let { stringAnnotation ->
                        mUriHandler.openUri(stringAnnotation.item)
                    }
            }
        )
    }
}
  
// For displaying preview in 
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MainContent()
}


第 3 步:使用 MainActivity.kt 文件

转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。

科特林

package com.geeksforgeeks.jctextspanhyperlink
  
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // Calling the composable function
            // to display element and its contents
            MainContent()
        }
    }
}
  
// Creating a composable 
// function to display Top Bar
@Composable
fun MainContent() {
    Scaffold(
        topBar = { TopAppBar(title = { Text("GFG | Text Span Hyperlink", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
        content = { MyContent() }
    )
}
  
// Creating a composable function 
// to create a Clickable Text
// Calling this function as content
// in the above function
@Composable
fun MyContent(){
  
    // Creating an annonated string
    val mAnnotatedLinkString = buildAnnotatedString {
  
        // creating a string to display in the Text
        val mStr = "Click this link to go to web site"
        
        // word and span to be hyperlinked
        val mStartIndex = mStr.indexOf("link")
        val mEndIndex = mStartIndex + 4
        
        append(mStr)
        addStyle(
            style = SpanStyle(
                color = Color.Blue,
                textDecoration = TextDecoration.Underline
            ), start = mStartIndex, end = mEndIndex
        )
  
        // attach a string annotation that 
        // stores a URL to the text "link"
        addStringAnnotation(
            tag = "URL",
            annotation = "https://www.geeksforgeeks.org",
            start = mStartIndex,
            end = mEndIndex
        )
  
    }
  
    // UriHandler parse and opens URI inside 
    // AnnotatedString Item in Browse
    val mUriHandler = LocalUriHandler.current
  
    Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
  
        // ???? Clickable text returns position of text 
        // that is clicked in onClick callback
        ClickableText(
            text = mAnnotatedLinkString,
            onClick = {
                mAnnotatedLinkString
                    .getStringAnnotations("URL", it, it)
                    .firstOrNull()?.let { stringAnnotation ->
                        mUriHandler.openUri(stringAnnotation.item)
                    }
            }
        )
    }
}
  
// For displaying preview in 
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MainContent()
}

输出:

您可以看到超链接是在显示“链接”一词的文本跨度上创建的。