【发布时间】:2022-01-12 21:48:59
【问题描述】:
我正在尝试使用 Kotlin 从我的 Assets 文件夹中读取一个文本文件并将其显示到 Compose text 小部件。 Android Studio 北极狐 2020.3
以下代码成功运行并将文本文件显示到输出控制台,但是我不知道如何获取文本文件并将其传递给 Compose 文本小部件。
您会注意到我在 ReadDataFile() 中有 2 个 text() 调用。第一个 text() 在 try{} 之外并且可以正常工作,但是 try{} 内的 text() 会导致错误:“Try catch is not supported around composable function invocations”
我怎样才能做到这一点?
谢谢!
package com.learning.kotlinreadfile
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import com.learning.kotlinreadfile.ui.theme.KotlinReadFileTheme
import java.io.InputStream
import java.io.IOException
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KotlinReadFileTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
ReadDataFile()
}
}
}
}
}
@Composable
fun ReadDataFile() {
println("Read Data File")
Text("Read Data File")
val context = LocalContext.current
try {
val inputStream: InputStream = context.assets.open("data.txt")
val size: Int = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
var string = String(buffer)
println(string)
//Text(string) // ERROR: Try catch is not supported around composable function invocations
} catch (e: IOException) {
e.printStackTrace()
println("Error")
}
}
【问题讨论】:
-
尝试在 try/catch 之后放置 //Text(string)。另外,把它换成 Column
-
@Alexander:做到了!
标签: kotlin android-jetpack-compose