[英]how to create a new variable every time inside a for a loop in kotlin
我有一个 for 循环,它在每次循环时创建一个cardView
,然后它对每个具有不同 extras 的视图使用setOnClickListener
,问题是只有最后一个循环参数被设置为每个创建的卡片,这是我的代码:
for (finalItem1 in finalList1) {
thePoints.clear()
theSteps.clear()
theIcons.clear()
val step1 =
"${getString(R.string.from_your_location)} \n ${getString(R.string.move_to)} \n $theStartStation"
theSteps.add(step1)
theIcons.add("ic_walk")
thePoints.add(stationData[theStartStation]?.latitude.toString())
thePoints.add(stationData[theStartStation]?.longitude.toString())
val step2 =
"${getString(R.string.from)} : $theStartStation \n ${getString(R.string.take)} : ${finalItem1.child("transportation_type").value} \n ${finalItem1.child("notes").value} \n ${finalItem1.child("price").value} EGP \n ${getString(R.string.to)} : $theEndStation"
theSteps.add(step2)
theIcons.add("ic_bus")
thePoints.add(stationData[theEndStation]?.latitude.toString())
thePoints.add(stationData[theEndStation]?.longitude.toString())
val cardView = CardView(this)
val cardLinearLayout = LinearLayout(this)
cardLinearLayout.orientation = LinearLayout.VERTICAL
val params = RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
params.setMargins(16, 16, 16, 16)
cardView.radius = 15f
cardView.setCardBackgroundColor(Color.parseColor("#64b0e3"))
cardView.setContentPadding(36, 36, 36, 36)
cardView.layoutParams = params
cardView.cardElevation = 30f
val quote = TextView(this)
quote.text = "${getString(R.string.from)} $theStartStation \n ${finalItem1.child("notes").value} \n ${finalItem1.child("price").value} EGP"
cardLinearLayout.addView(quote)
cardView.addView(cardLinearLayout)
optionsLayout.addView(cardView)
cardView.setOnClickListener {
val tripIntent =
Intent(this, NavigationActivity::class.java)
tripIntent.putStringArrayListExtra("theSteps",
theSteps as java.util.ArrayList<String>?
)
tripIntent.putStringArrayListExtra("theIcons",
theIcons as java.util.ArrayList<String>?
)
tripIntent.putStringArrayListExtra("thePoints",
thePoints as java.util.ArrayList<String>?
)
tripIntent.putExtra("fromLat", fromLocation.latitude)
tripIntent.putExtra("fromLon", fromLocation.longitude)
tripIntent.putExtra("toLat", toLocation.latitude)
tripIntent.putExtra("toLon", toLocation.longitude)
startActivity(tripIntent)
}
问题出在这里: val cardView = CardView(this)
因为它为每张卡片创建了相同的监听器cardView.setOnClickListener
每个侦听器实例都引用在循环外声明的theSteps
、 theIcons
和theIcons
对象。 您清除这些列表,然后在每次循环迭代中向它们添加项目,因此实际上只使用上次迭代的值。 只需在循环中声明这些列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.