我正在建立一个基于别人代码的媒体播放器。 媒体播放器播放资产文件夹中的mp3。 我已将ListView添加到媒体播放器layout.xml,并希望使用asset文件夹的内容填充此列表。 目前主java中有一些代码采用mp3名称并在弹出窗口中显示。如何将此信息加载到列表中。列表中的ietm必须与曲目播放相对应。
这是java代码
//Generate a String Array that represents all of the files found
private String[] getTracks(){
if(type == 0){
try {
String[] temp = getAssets().list("");
return temp;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
} else if(type == 1){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String[] temp = path.list();
return temp;
} else{
Toast.makeText(getBaseContext(), "SD Card is either mounted elsewhere or is unusable", Toast.LENGTH_LONG).show();
}
}
return null;
}
//Adds the playable files to the trackNames List
private void addTracks(String[] temp){
if(temp != null){
for(int i = 0; i < temp.length; i++){
//Only accept files that have one of the extensions in the EXTENSIONS array
if(trackChecker(temp[i])){
trackNames.add(temp[i]);
trackArtworks.add(temp[i].substring(0, temp[i].length()-4));
}
}
Toast.makeText(getBaseContext(), "Loaded " + Integer.toString(trackNames.size()) + " Tracks", Toast.LENGTH_SHORT).show();
}
}
//Plays the Track
private void playTrack(){
if(isTuning && track != null){
track.play();
Toast.makeText(getBaseContext(), "Playing " + trackNames.get(currentTrack).substring(0, trackNames.get(currentTrack).length()-4), Toast.LENGTH_SHORT).show();
}
}
我的xml
<ListView
android:id="@+id/trackNames"
android:layout_width="match_parent"
android:layout_height="98dp"
android:layout_weight="0.74" >
</ListView>
如何填充列表?我怎么能用我已有的代码呢?
答案 0 :(得分:0)
您需要创建一个ArrayAdapter或ArrayAdapter的子类,将数据添加到它,并在ListView中设置它。
这是example.
答案 1 :(得分:0)
这是一个SimpleAdapter版本....非常类似于ArrayAdapter
HashMap<String,String> item;
for (int i=0;i<count; i++){
item = new HashMap<String,String>();
item.put( "line1", trackNames.get(i));
list.add( item );
}
sa = new SimpleAdapter(getActivity(),
list, android.R.layout.simple_list_item_activated_1, new String[] { "line1" }, new int[] {android.R.id.text1});
setListAdapter( sa );