我有一个for循环,每次循环都会创建一个cardView
,然后它为每个具有不同附加功能的视图使用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
创建了相同的侦听器
答案 0 :(得分:0)
每个侦听器实例都引用在循环外部声明的theSteps
,theIcons
和theIcons
对象。您清除这些列表,然后在每个循环迭代中向其中添加项目,因此实际上仅使用上一次迭代中的值。只需在循环中声明这些列表即可。