前几天有人向我要音乐播放器源代码 而自己因为系统问题而丢失了 所以决定重写一遍
为了与以前不同 所以今天打算不用ListView 而用RadioGroup 其实是换汤不换药而已
[代码 步骤]
1. 定制化有RadioGroup的界面:main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/cmd"
android:layout_width="wrap_content"
android:layout_height="500dip"
android:text="Loading.."
/>
</LinearLayout>
<RadioGroup
android:id="@+id/rgroup"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
2. 初始化所有View
public void initialView(){
rGroup = (RadioGroup) findViewById(R.id.rgroup);
cmd = (Button) findViewById(R.id.cmd);
}
3. 检索MediaStore 得到sdcard所以音乐的Uri
Cursor c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, null, null, null);
4. 把上面的音乐文件装入RadioButton
public void loadMusic(Cursor c){
int index = c.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
int i=BASE_ID;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
String title = c.getString(index);
RadioButton rb = new RadioButton(this);
rb.setText(title);
rb.setId(i++);
rGroup.addView(rb);
}
}
5. 设立RadioGroup的选择监听器 并播放选中目标
rGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int id = group.getCheckedRadioButtonId()-BASE_ID+1;
try {
playMusic(id);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
public void playMusic(long arg3) throws IllegalArgumentException, IllegalStateException, IOException{
Uri uri = Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
String.valueOf(arg3));
mPlayer.release();
mPlayer = MediaPlayer.create(this, uri);
mPlayer.start();
}
5. emulator 运行截图: