You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin使用Retrofit解析JSON并将响应展示到TextView的问题求助

问题2 将解析结果设置到TextView

首先在你的MainActivity布局文件中给要展示内容的TextView设置id,比如tv_quote(展示名言)、tv_author(展示作者),然后修改getQuotes方法:

fun getQuotes() {
    val apiService = RestApiService()
    val userInfo = UserInfo("","")

    apiService.addUser(userInfo) { result ->
        if (result != null) {
            // Retrofit回调默认运行在主线程,可直接给控件赋值
            findViewById<TextView>(R.id.tv_quote).text = result.quote
            // 作者为空时默认展示佚名
            findViewById<TextView>(R.id.tv_author).text = result.author.ifEmpty { "佚名" }
        } else {
            Log.d("getQuotesError","请求失败")
            Toast.makeText(this, "获取名言失败", Toast.LENGTH_SHORT).show()
        }
    }
}

注意:请确保你已经在AndroidManifest.xml中添加了网络权限:<uses-permission android:name="android.permission.INTERNET" />,否则请求会直接失败。


内容的提问来源于stack exchange,提问作者Khurria_55

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:15:04