You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android音乐播放器开发报错求助:RecyclerView与导入问题

Android音乐播放器问题排查与解决

一、kotlinx.android.synthetic导入标红问题

这是因为Kotlin Android Extensions插件已被官方废弃,当前推荐使用View Binding替代。如果仍想临时使用该插件,需确保项目配置正确:

  • 项目根目录build.gradle(Project级)中确认Kotlin插件依赖:
buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:你的Kotlin版本号"
    }
}
  • 模块目录build.gradle(Module级)中启用插件:
apply plugin: 'kotlin-android-extensions'

更推荐的View Binding迁移方案

  1. 在模块build.gradle中启用View Binding:
android {
    ...
    buildFeatures {
        viewBinding true
    }
}
  1. 修改MainActivity代码,替换Kotlin扩展:
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 原recycler_view改为binding.recyclerView(需与xml中RecyclerView的id一致)
        val layoutManager = LinearLayoutManager(applicationContext)
        binding.recyclerView.layoutManager = layoutManager
        songListAdapter?.let {
            binding.recyclerView.adapter = it
        }
    }
}

二、RecyclerView代码报错问题

1. 属性名大小写错误

你代码中recycler_view.LayoutManager = layoutManager的LayoutManager首字母大写,RecyclerView的标准属性是小写的layoutManager,修正为:

recycler_view.layoutManager = layoutManager

2. 可空类型适配问题

songListAdapter被声明为可空类型(SongListAdapter?=null),但RecyclerView.adapter要求非空对象,可通过以下方式解决:

// 方式1:非空断言(确保songListAdapter已初始化时使用)
recycler_view.adapter = songListAdapter!!

// 方式2:安全调用+let(更安全)
songListAdapter?.let {
    recycler_view.adapter = it
}

3. Adapter构造函数优化

原Adapter构造函数参数名与类名重名,易引发混淆,建议修改:

class SongListAdapter(private val songList: ArrayList<SongModel>) : RecyclerView.Adapter<SongListAdapter.SongListViewHolder>() {
    override fun getItemCount(): Int {
        return songList.size
    }

    // 其余代码不变
}

额外优化建议

  1. 关闭Cursor避免内存泄漏:
    Cursor使用后必须关闭,推荐用use函数自动管理:
contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)?.use { cursor ->
    while (cursor.moveToNext()) {
        val songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
        val songDuration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
        songModelData.add(SongModel(songName, formatDuration(songDuration)))
    }
}
  1. 时长格式化:
    MediaStore返回的duration是Long类型(毫秒),直接转String会显示纯数字,建议添加格式化函数:
private fun formatDuration(duration: Long): String {
    val minutes = (duration / 1000) / 60
    val seconds = (duration / 1000) % 60
    return String.format("%02d:%02d", minutes, seconds)
}

内容的提问来源于stack exchange,提问作者ADES GAMES

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 23:10:53