为什么我的功能不允许我为ImageView
设置内容描述?似乎可以让我设置可绘制资源和文本。
class MyAdapter(
private val dataIVPlayOrPause: Drawable,
private val dataTVSong: String
) : RecyclerView.Adapter<RVAdapterEmbark.MyViewHolder>() {
private val typeHeader = 1
private val typeItem = 2
override fun onCreateViewHolder(parent: ViewGroup, type: Int): MyViewHolder {
return when (type) {
typeHeader -> MyViewHolder(inflateHelper(R.layout.header, parent))
typeItem -> MyViewHolder(inflateHelper(R.layout.body, parent))
else -> MyViewHolder(inflateHelper(R.layout.body, parent))
}
}
override fun onBindViewHolder(viewHolder: MyViewHolder, position: Int) {
if (getItemViewType(position) == typeHeader) {
} else if (getItemViewType(position) == typeItem) {
val ivPlayPause = viewHolder.itemView. iv_Play_Pause
ivPlayPause(R.drawable.play)
ivPlayPause = R.string.play.toString()
val buttonClickListener = View.OnClickListener {
if (tvSongName.text == null) {
playSong(tvSongName, ivPlayPause)
} else {
pauseSong(tvSongName, ivPlayPause)
}
}
}
}
private fun inflateHelper(resId: Int, parent: ViewGroup): View {
return LayoutInflater.from(parent.context).inflate(resId, parent, false)
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun getItemCount(): Int {
return dataTitle.size + 1
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) typeHeader
else typeItem
}
private fun playSong(
tvSongName: TextView,
ivPlayPause: ImageView
) {
tvSongName.text = "Song name"
ivPlayPause.setImageResource(R.drawable.pause)
ivPlayPause.contentDescription = getString(R.string.pause)
}
}
由于您在RecyclerView.Adapter
中,因此无法访问声明了Activity
的Fragment
,Context
或getString()
实例。
在这种情况下,您可以使用Context
中的ImageView
获取字符串:
ivPlayPause.contentDescription = ivPlayPause.context.getString(R.string.pause)