【发布时间】:2016-05-07 20:20:06
【问题描述】:
我正在为安卓制作一个小型 MP3 播放器。 对于我的项目,我编写了一个类 (MP3Finder),它在 HashMap 的 ArrayList 中返回定位的歌曲。
到目前为止,我的应用程序只显示位于 sdcard 上的歌曲 在用户可以开始播放歌曲的列表视图中。
现在我希望用户能够将不同的歌曲添加到播放列表中。 出于这个原因,我使用包含所有 歌曲作为checkedTextView 项目。 问题是我不知道如何存储歌曲列表中选中的(用户选择的)歌曲 返回到 HashMap 的 ArrayList 中,该 ArrayList 将被发送到播放列表活动。 我希望你明白我想做什么。
这是我的 SongListActivity 的源代码:
public class SongListActivity extends AppCompatActivity {
// List of mp3 files
ArrayList<HashMap<String, String>> MP3List = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button isChecked = (Button) findViewById(R.id.btn_is_checked);
final ListView listView = (ListView) findViewById(R.id.list_view);
MP3Finder mp3Finder = new MP3Finder();
// Get all mp3's from sdcard
this.MP3List = mp3Finder.getMP3List();
// Add items to ListView
ListAdapter adapter = new SimpleAdapter(this, MP3List, R.layout.activity_item, new String[] { "mp3Title" }, new int[] {
R.id.mp3_title});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new CheckBoxClick());
listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
isChecked.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
int len = listView.getCount();
for (int i = 0; i < len; i++) {
if (checked.get(i)) {
// ...here is the part, where I want to store the selected songs back
// in an ArrayList of HashMap...
}
}
}
});
}
public class CheckBoxClick implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView checkedTextView = (CheckedTextView) view;
if (checkedTextView.isChecked()) {
Toast.makeText(MainActivity.this, "checked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "unchecked", Toast.LENGTH_SHORT).show();
}
}
}
任何帮助或建议将不胜感激。
【问题讨论】:
-
不应该是 Hashmap
其中 string 将是播放列表名称,而 ArrayList 将包含歌曲列表? -
你好安舒尔。不,在我的项目中,我使用了 HashMap
其中第一个字符串(键)应该是歌曲的路径,第二个字符串应该是艺术家和歌曲的标题。也许你不明白我到底想知道什么。为了使用来自 ArrayList 的数据填充 ListView 项目,我使用了 SimpleAdapter。我想知道的是回来的路。我的意思是如何从列表视图中填充 Hashmap 的 ArrayList。请你能解释一下我该怎么做吗?也许举个小例子。
标签: java android listview arraylist hashmap