android - 从 JSON 到 Kotlin 的图像
问题描述
JSON 列表始终包含两个图像名称之一(一个.png 或两个.png)。请说明如何让这个图像出现在应用程序中(在项目中,这两个图像已经在\src\main\res\mipmap-hdpi中)。
Json 文件如下所示:
{"Api":[{"Info":"Random text","Img":"one.png","Desc":"Alarm","TimeStamp":1626010201}]}
Kotlin 的项目,我刚刚开始学习它。
在php中我会写这样的东西:
$onepng = \sic\home\res\mipmap-hdi\one.png; // path in the project to 'one.png'
$twopng = \sic\home\res\mipmap-hdi\two.png; // path in the project to 'two.png'
$ImgOneTwo = (JSON IMG == one.png) ? $onepng : $twopng;```
In layout:
```<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="@+id/ImgOneTwo"
android:src="@mipmap/one">
</ImageView>```
解决方案
您可以使用 if-else 语句从 api 获取响应后显示相应的图像。假设您正在使用改造来获取 JSONArray,您可以这样做:
val retrofitBuilder = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(YourApiInterface::class.java)
val retrofitData = retrofitBuilder.getJSONArray()
retrofitData.enqueue(object : Callback<ApiResponse?> {
override fun onResponse(
call: Call<ApiResponse?>,
response: Response<ApiResponse?>
) {
if (response.body()!!.api[0].Img == "one.png") {
imageView.setImageResource(R.drawable.one)
} else {
imageView.setImageResource(R.drawable.two)
}
}
override fun onFailure(call: Call<ApiResponse?>, t: Throwable) {
Log.v("Ret fail", t.message.toString())
}
})
推荐阅读
- qt - 如何在 QML Controls 2 TableView 中获取元素位置
- php - Opencart 3.x - 以奖励积分显示价格 - 特色主页
- angular - 为什么在 ngx-modal 中提交表单时没有表单值?
- mrtk - 在 Unity 中使用 Windows Mixed Reality 控制器的操纵杆 (teletrasport)
- microservices - 微服务应用程序的最佳实践
- javascript - 我的导航栏在 microsoft edge 中工作,但在 chrome 中不好
- r - 为什么这个 webhook 在 RStudio 中有效,但在命令行中无效?
- nativescript - 无法以编程方式在 Nativescript ProxyViewContainer 上设置边距
- postgresql - 如何将最后插入或更新的条目标记为“活动”
- html - Django中用于登录AuthenticationForm的占位符不显示