有没有干净的干净的方式来从HTTP请求JSON更新多个textViews?
我有以下Kotlin / Anko / Android活动。
import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.TextView import com.fasterxml.jackson.module.kotlin.readValue import com.github.kittinunf.fuel.Fuel import eu.gwapi.laaketilaus.util.JSON import eu.gwapi.laaketilaus.util.Order import org.jetbrains.anko.find import org.jetbrains.anko.textView import org.jetbrains.anko.toast import org.jetbrains.anko.verticalLayout class OrderDetailsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val order_id: Long = intent.extras.getLong("order_id") verticalLayout { textView { id = R.id.order_detail_customer } textView { id = R.id.order_detail_address } textView { id = R.id.order_detail_postal_code } textView { id = R.id.order_detail_phone } } getOrder(order_id) } fun getOrder(order_id: Long) { Fuel.get("https://my.api.endpoint/" + order_id.toString()).responseString { request, response, result -> val (json, err) = result if (err != null) { toast(err.toString()) } else { val order: Order = JSON.readValue(json!!) find(R.id.order_detail_customer).text = order.customer find(R.id.order_detail_address).text = order.address find(R.id.order_detail_postal_code).text = order.postal_code find(R.id.order_detail_phone).text = order.phone } } } }
对于像我这样顽固的pythonista来说,这似乎是非常静态和冗长的做法。
有没有更好的办法?
由于只有TextView
,你只需要改变他们的文本,你可以通过以下方式简化你的代码:
-
为存储ID的
Order
属性添加映射:private val orderPropertyToTextViewId = mapOf( Order::customer to R.id.order_detail_customer, Order::address to R.id.order_detail_address, Order::postalCode to R.id.order_detail_postal_code, Order::phone to R.id.order_detail_phone )
-
创建在地图上迭代的视图:
verticalLayout { for ((property, textViewId) in orderPropertyToTextViewId) { textView { id = textViewId } } }
-
更新在地图上迭代的文本:
for ((property, textViewId) in orderPropertyToTextViewId) { findViewById
(textViewId).text = property.get(order) }
如果存储由textView { ... }
调用返回的TextView
而不是地图中的ID,则可以进一步去掉ID并findfindViewById
,但这需要进一步的实验。
如果您不需要经常刷新新数据,则不需要保留对TextView
引用。 我不使用Anko,但它可能看起来像:
val order: Order = JSON.readValue(json!!) verticalLayout { arrayOf(order.customer, order.address, order.postal_code, order.phone) .map { textView { text = it } } }