我想从ViewHolder的itemView clicklistener设置TextView文本。我尝试在Activity类中创建伴侣对象,并尝试从ViewHolders itemView clicklistener调用它。但是在同伴对象内部,我无法访问布局中的TextView对象
以下是用于设置 recyclerview
的适配器代码class QnAdapter(val context: Context, val ques: List<QnoList>):
RecyclerView.Adapter<QnAdapter.ViewHolder>(){
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder{
val view = LayoutInflater.from(context).inflate(R.layout.recycler_qno, p0, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return ques.size
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int){
val question = ques[p1]
p0.setData(question, p1)
}
inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var currentQ: QnoList?=null
var currentQno: Int =0
init{
itemView.setOnClickListener{
Toast.makeText(context,currentQ!!.qno.toString()+" Selected",Toast.LENGTH_SHORT).show()
var a1 = MCQActivity
a1.setText(context)
a1.setTxt() // here I want to set TextView, present in Layout of activity(not of recyclerview) text from recyclerview event
}
}
fun setData(ques:QnoList?,p1:Int){
itemView.rqno.text = ques!!.qno.toString()
this.currentQ = ques
this.currentQno = p1+1
}
}
}
private fun MCQActivity.Companion.setTxt() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
以下是activity
类代码
class MCQActivity : AppCompatActivity() {
companion object {
fun setText(context: Context){
Toast.makeText(context, "Hi I am called", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mcq)
setRecyclerView()
}
open fun setRecyclerView(){
val layoutmanager = LinearLayoutManager(this)
layoutmanager.orientation= LinearLayoutManager.HORIZONTAL
recycler_qno.layoutManager = layoutmanager
val adapter = QnAdapter(this, mcq.queslst)
recycler_qno.adapter = adapter
}
}
答案 0 :(得分:0)
当然,您不能通过伴随对象访问TextView
。
首先,您应该了解伴随对象的定义。它是该类或任何其他类的所有实例共有的对象。它会类似于Java中的静态字段。它没有为该类创建的任何对象的引用。
那么如何解决您的问题?
由于您已经将上下文传递给QnAdapter
,并且我想它是MCQActivity
的实例/对象,因此可以将该上下文转换为MCQActivity
并为该实例设置文本。
请参考此代码
class MCQActivity : AppCompatActivity() {
fun setText(theTextYouWantToSet: String) {
findViewById<TextView>(R.id.textView).text = theTextYouWantToSet
}
}
class QnAdapter(val context: Context, val ques: List<String>) : RecyclerView.Adapter<QnAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
(context as MCQActivity).setText("I am handsome")
}
}
}
}
答案 1 :(得分:0)
companion
函数与Java
中的静态函数相同。在这种情况下,您应该删除伴随对象,并在setText
中将MCQActivity
函数公开。
要从ViewHolder
访问您的活动,很简单:
(itemView.context as? MCQActivity)?.setText("I am handsome")