1

我正在基于别人的代码构建一个媒体播放器。媒体播放器播放资产文件夹中的 mp3。我已将 ListView 添加到媒体播放器 layout.xml 并希望使用资产文件夹的内容填充此列表。目前在主 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>

如何填充列表?我怎样才能使用我已经拥有的代码来做到这一点?

4

2 回答 2

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 );
于 2013-04-05T18:57:48.913 回答
0

您需要创建一个 ArrayAdapter 或 ArrayAdapter 的子类,将您的数据添加到其中,并将其设置在您的 ListView 中。

这是一个例子。

于 2013-04-05T18:20:10.173 回答