gpt4 book ai didi

android - 媒体播放器和 RecyclerView kotlin

转载 作者:行者123 更新时间:2023-11-29 02:22:28 24 4
gpt4 key购买 nike

我正在尝试使用 RecyclerView Adapter 和 DataService 创建一个简单的音频播放器,但在初始化 MediaPlayer 阶段遇到了困难。

我添加了数据服务:

object DataService {
val unitOneSound = listOf(
SoundScreen("Song 1", R.raw.song1),
SoundScreen("Song 2", R.raw.song2),
SoundScreen("Song 3", R.raw.song3),
SoundScreen("Song 4", R.raw.song4),
SoundScreen("Song 5", R.raw.song5),
SoundScreen("Song 6", R.raw.song6)
)

val unitTwoSound = listOf(
SoundScreen("Song 7", R.raw.song7),
SoundScreen("Song 8", R.raw.song8),
SoundScreen("Song 9", R.raw.song9),
SoundScreen("Song 10", R.raw.song10),
SoundScreen("Song 11", R.raw.song11),
SoundScreen("Song 12", R.raw.song12)
)

val listOfSounds = listOf<SoundScreen>()

fun getSong(activity: String) : List<SoundScreen>{
return when(activity){
"Audio files 1" -> unitOneSound
"Audio files 2" -> unitTwoSound
else -> listOfSounds
}
}

Adapter(应该在这里初始化)

class RecyclerSoundScreenAdapter(val context: Context, val song: List<SoundScreen>, val itemClick: (SoundScreen) -> Unit):  RecyclerView.Adapter<RecyclerSoundScreenAdapter.Holder>() {

override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bindActivity(song[position], context)
}

override fun getItemCount(): Int {
return song.count()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(context).inflate(R.layout.sound_template, parent, false)
return Holder(view, itemClick)
}

inner class Holder(itemView: View, val itemClick: (SoundScreen) -> Unit) : RecyclerView.ViewHolder(itemView) {
val songName = itemView.findViewById<TextView>(R.id.sound_text_view)
val buttonPlay = itemView.findViewById<Button>(R.id.buttonPlay)

fun bindActivity(sound: SoundScreen, context: Context) {
songName.text = sound.songTitle
itemView.setOnClickListener{itemClick(sound)}
}
}
}

SoundActivity: (然后我觉得应该在这里调用,就在DataService.getSong(songType)之后){sound ->)

class SoundActivity : AppCompatActivity() {

lateinit var adapter: RecyclerSoundScreenAdapter

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

val songType = intent.getStringExtra(EXTRA_ACTIVITY)
adapter = RecyclerSoundScreenAdapter(this, DataService.getSong(songType)){sound ->

}

val layoutManager = LinearLayoutManager(this)
soundListView.layoutManager = layoutManager
soundListView.adapter = adapter
}
}

最佳答案

您可以在您声明的 OnClickListener 调用的 itemClick 函数中初始化 MediaPlayer。

您可以检查该线程: Android how to stop media player when new sound start in Recycleview

关于android - 媒体播放器和 RecyclerView kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54522759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com