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
相关产品推荐
相关产品推荐

