我在第一项活动(listView)上有一个按钮,可将您带到第二项活动(将在其中添加与该单击的项目有关的图像)。如何在适配器的getView方法中设置onClick事件?
适配器
class ChallengeListAdapter: BaseAdapter {
private var challengeDatabase: ChallengeDatabase? = null
private var context: Context? = null
constructor(context: Context) {
challengeDatabase = ChallengeDatabase()
this.context = context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val challenge: Challenge = challengeDatabase?.challengesList?.get(position)
?: Challenge(
"No Name", "No Description")
var challengeView: View
var layoutInflater: LayoutInflater = context?.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
challengeView = layoutInflater.inflate(R.layout.challenge_row, null)
challengeView.lblChallengeName.setText(challenge.name)
challengeView.lblChallengeDesc.setText(challenge.desc)
return challengeView
}
override fun getItem(position: Int): Any {
return challengeDatabase?.challengesList?.get(position) ?: Challenge(
"No Name", "No Des")
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return challengeDatabase?.challengesList?.size ?: 0
}
}
我该如何解决?
challengeView.setOnClickListener {
val solutionButton: Button = findViewById(R.id.solution_button)
val Intent = Intent(context, SolutionActivity::class.java)
Intent.putExtra()
startActivity(context!!, Intent, null)
return challengeView
答案 0 :(得分:1)
正如Furqan所说,您将点击侦听器设置为该项的视图。在这种情况下,请将其设置为challengeView
。
要从中打开活动,您需要将所需的信息放入捆绑包中,并创建一个意图以使用该活动来打开活动。您可以从视图的上下文开始活动,也可以将该事件传播给适配器的所有者,直到到达活动并从那里开始(通常,如果要寻求职责分工,通常会更好)。
以更惯用的方式编写它的一些技巧:
LayoutInflater.from(parent.context)
.inflate(R.layout.challenge_row, null)
challengeView
不可变,甚至可以像这样内联:...
return LayoutInflater.from(parent.context)
.inflate(R.layout.challenge_row, null)
?.apply {
lblChallengeName.text = challenge.name
lblChallengeDesc.text = challenge.desc
setOnClickListener {
//add your code to load activity
}
}
challangeDatabase
可以是val
且不能为空private val challengeDatabase = ChallengeDatabase()
答案 1 :(得分:1)
您需要处理Adapter setOnClickListener的参数
challengeView.setOnItemClickListener { parent, view, position, id ->
val element = adapter.getItemAtPosition(position) // The item that was clicked
val intent = Intent(this, SolutionActivity::class.java)
intent.putExtra("key", element)
startActivity(intent)
}
答案 2 :(得分:0)
将此添加到您的getView方法
Audio
现在添加您的getView方法将类似于
var myAlarm = new Audio("https://freesound.org/data/previews/470/470504_2694940-lq.mp3");
myAlarm.play();
确保您的挑战类实现了可序列化