首页 > 解决方案 > 从 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>```

标签: androidjsonkotlinresources

解决方案


您可以使用 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())
        }
    })

推荐阅读