媒体播放器和RecyclerView Kotlin

时间:2019-02-04 19:07:44

标签: android kotlin

我正在尝试使用RecyclerView Adapter和DataService创建一个简单的音频播放器,但是在初始化MediaPlayer阶段很费劲。

我添加了DataService:

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
        }
    }

适配器(应在此处初始化)

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
    }
}

1 个答案:

答案 0 :(得分:0)

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

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