最近我在学习在学习RecyclerView,跟着老司机玩转App,《Android App 开发入门与项目实战》很友好,比较适合新手入门,通过基础知识和案例相结合,慢慢掌握其中要点。
书中的音乐案例在我的Android Studio模拟器中运行,从媒体库MediaStore.Audio.Media.EXTERNAL_CONTENT_URI加载音频文件列表,显示只有两首歌曲,无论我怎么重启模拟器,结果还是如此。于是我选择从sdcard/Music下遍历文件,通过适配器加载到RecyclerView中。
[案例代码仓库](https://codechina.csdn.net/mirrors/aqi00/myapp) 推荐购买书籍来上手。
运行书中的案例,结果如下,显示模拟器中的两首歌曲,实际导入了9首。
一番操作之后,可以显示完整的音乐列表,除了最佳损友不能播放,或许是MediaPlayer不喜欢损友爱基友。
以下是具体的步骤:
1、AndroidManifest.xml加载存储卡读写权限:
<!-- 存储卡读写 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
运行在Android 10及更高版本手机,配置暂时停用分区存储。
<application android:requestLegacyExternalStorage=“true”
2、申请动态权限:方式一、用代码来申请权限;方式二、可以在手机设置中手动打开如下的权限。
3、写出每个音乐条目布局,没有点击播放时隐藏进度条,点击之后显示它。因为是progressBar,所以无法拖动播放进度。
item_audio.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_audio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="left|center"
android:textColor="@color/black"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_duration"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="right|center"
android:textColor="@color/black"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_progress"
android:layout_width="match_parent"
android:layout_height="30dp"
android:orientation="horizontal"
android:visibility="gone">
<ProgressBar
android:id="@+id/pb_audio"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
<TextView
android:id="@+id/tv_progress"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="right|center"
android:textColor="@color/black"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
4、主界面显示RecyclerView布局。
activity_audio_play.xml
<LinearLayout xmlns:android="http://schemas.android