如何显示 api 中只有单一数据的数据?

How can I show data from api which has single data only?

我是kotlin新手,找不到相关解决方案。 我想要做的是从 api(金额和货币)获取数据并在点击时显示。 我能够循环数据,但我不知道如何取消循环。

api 的回复是这样的:

{
    "data": {
        "amount": 825,
        "currency": "hkd"
    }
}

我的模特:

data class MainData(
    var data: AmountData
)

data class AmountData(
    val amount: Int,
    val currency: String,
)

我的 API 服务:

interface ApiService {

    @GET("posts")
    fun getPosts(): Call<MutableList<PostModel>>

    @GET("checkout/vend/CLIENT_ID/payment/request")
    fun paymentRequest(): Call<MainData>
}

我的适配器:

class PaymentAdapter(private val mainData: MainData): RecyclerView.Adapter<PaymentViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.card_post, parent, false)
        return PaymentViewHolder(view)
    }

    override fun onBindViewHolder(holder: PaymentViewHolder, position: Int) {
        return holder.bindView(mainData) // I don't even know how to bind the data
    }

    override fun getItemCount(): Int {
        return mainData.data.amount // This is also incorrect but I don't know what to do
    }
}

class PaymentViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){

    private val tvAmount: TextView = itemView.findViewById(R.id.tvAmount)
    private val tvCurrency: TextView = itemView.findViewById(R.id.tvCurrency)

    fun bindView(mainData: MainData){
        tvAmount.text = mainData.data.amount.toString()
        tvCurrency.text = mainData.data.currency
    }
}

这是目前的result

因为你只有 1 件物品,所以你总是可以做

override fun getItemCount(): Int {
    return 1
}

它可能已经给出了您想要的结果

不过,确实没有必要为此使用RecyclerView。我会删除 RecyclerView 并只添加两个 TextView 或其他内容。