【发布时间】:2016-12-20 19:14:05
【问题描述】:
我真的被困在这里,我是编程新手。 我在我的音乐应用程序中取得了很多成就,但现在我在我的 listViewAdapter 中使用 OnClickListener 制作了一个按钮,我想在我的 MainActivity 中的 favList ArrayList 中添加一首歌曲。有了这个代码,我就有了我想要的歌曲,但我如何将它放入列表中?
这是我的代码:
class SongAdapter extends ArrayAdapter<Song> {
SongAdapter(Context context, ArrayList<Song> songs) {
super(context, 0, songs);
}
@NonNull
@Override
public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
Song currentSong = getItem(position);
TextView songNameTextView = (TextView) listItemView.findViewById(R.id.song_name);
assert currentSong != null;
songNameTextView.setText(currentSong.getSongName());
TextView songArtistTextView = (TextView) listItemView.findViewById(R.id.song_artist);
songArtistTextView.setText(currentSong.getArtist());
ImageButton addToPlaylistButton = (ImageButton) listItemView.findViewById(R.id.addToPlaylist);
addToPlaylistButton.setTag(position);
addToPlaylistButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = (Integer) view.getTag();
Song song = getItem(position);
Toast.makeText(view.getContext(), song.getAlbum().toString(), Toast.LENGTH_LONG).show();
}
});
return listItemView;
} }
以下是我的 MainActivity 中的部分:
final ArrayList<Song> songs = new ArrayList<>(); final ArrayList<Song> favSongs = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_list);
//Setup the Listview for the Songs
SongAdapter adapter = new SongAdapter(this, songs);
ListView listView = (ListView) findViewById(R.id.list);
listView.setItemsCanFocus(true);
listView.setAdapter(adapter);
}
【问题讨论】:
标签: android adapter onclicklistener