如何在RecyclerView上添加点击处理程序?

时间:2019-05-04 16:22:53

标签: android kotlin android-recyclerview

我试图将点击处理程序添加到RecyclerView行中的一个视图中。

活动类:

class MainActivity : AppCompatActivity() {

private val newWordActivityRequestCode = 1
private lateinit var wordViewModel: WordViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toolbar = findViewById<Toolbar>(R.id.toolbar)
    setSupportActionBar(toolbar)

    val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
    val adapter = WordListAdapter(this)
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(this)

    wordViewModel = ViewModelProviders.of(this).get(WordViewModel::class.java)
    wordViewModel.allWords.observe(this, Observer { words ->
        words?.let { adapter.setWords(it) }
    })

    val fab = findViewById<FloatingActionButton>(R.id.fab)
    fab.setOnClickListener {
        val intent = Intent(this@MainActivity, NewWordActivity::class.java)
        startActivityForResult(intent, newWordActivityRequestCode)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, intentData: Intent?) {
    super.onActivityResult(requestCode, resultCode, intentData)

    if (requestCode == newWordActivityRequestCode && resultCode == Activity.RESULT_OK) {
        intentData?.let { data ->
            val word = Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY))
            wordViewModel.insert(word)
        }
    } else {
        Toast.makeText(
                applicationContext,
                R.string.empty_not_saved,
                Toast.LENGTH_LONG
        ).show()
    }
}

}

这是我的回收者视图类。

class WordListAdapter internal constructor(
    context: Context
) : RecyclerView.Adapter<WordListAdapter.WordViewHolder>() {

private val inflater: LayoutInflater = LayoutInflater.from(context)
private var words = emptyList<Word>() // Cached copy of words

inner class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val wordItemView: TextView = itemView.findViewById(R.id.textView)
    val wordUpdateView: ImageButton = itemView.findViewById(R.id.update_button)
    val wordDeleteView: ImageButton = itemView.findViewById(R.id.delete_button)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
    val itemView = inflater.inflate(R.layout.recyclerview_item, parent, false)
    return WordViewHolder(itemView)
}

override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
    val current = words[position]
    holder.wordItemView.text = current.word
}

internal fun setWords(words: List<Word>) {
    this.words = words
    notifyDataSetChanged()
}

override fun getItemCount() = words.size
}

我想为每个ImageButton的click事件添加功能。我的recyclerview布局是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/word_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="sans-serif"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="18sp"
    android:textStyle="bold" />

<Space
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_weight="1" />

<ImageButton
    android:id="@+id/update_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/update_item_content"
    android:src="@drawable/ic_edit_black_24dp" />

<ImageButton
    android:id="@+id/delete_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/delete_item_from_database"
    android:src="@drawable/ic_delete_black_24dp" />


</LinearLayout>

奖金问题:Activity(包含RecyclerView)持有对ViewModel对象的引用。最终,我需要访问该对象。我应该将该对象传递给RecyclerView吗?

1 个答案:

答案 0 :(得分:0)

将此添加到您的活动中:

class MainActivity : AppCompatActivity() {
    lateinit var action: View.OnClickListener // This will set your Variable which you gonna use later

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        action = View.OnClickListener {
           val wordImViewtxt = WordListAdapter.wordImViewtxt // Here you have the value of wordItemView
        }
    }

现在更改您传递给适配器的值,就像这样:

val adapter = WordListAdapter(this , action) // We Passed action here and you need to make changes for it in your adapter.

适配器:

class WordListAdapter internal constructor(context: Context, val action : View.OnClickListener) : RecyclerView.Adapter<WordListAdapter.WordViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var words = emptyList<Word>() // Cached copy of words
    var wordItemViewtxt = ""

    inner class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val wordItemView: TextView = itemView.findViewById(R.id.textView)
        val wordUpdateView: ImageButton = itemView.findViewById(R.id.update_button)
        val wordDeleteView: ImageButton = itemView.findViewById(R.id.delete_button)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
        val itemView = inflater.inflate(R.layout.recyclerview_item, parent, false)
        return WordViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
        val current = words[position]
        holder.wordItemView.text = current.word
        holder.wordUpdateView?.setOnClickListener({it->
            wordItemViewtxt = current.word // Passed value to this and use listener
            action.onClick(it)
        })
    }

    internal fun setWords(words: List<Word>) {
        this.words = words
        notifyDataSetChanged()
    }

    override fun getItemCount() = words.size
}

有问题请问我。