私は本当にここにこだわっています。私はプログラミングが初めてです。 私はMusic Appで多くのことを達成しましたが、今は、ListViewAdapterでOnClickListenerを使用してボタンを作成し、MainActivityのfavList ArrayListにSongを追加します。このコードでは、私が望むソングがありますが、どのようにリストに入れるのですか?ここでAndroid:アダプタからOnClickListenerのメインアクティビティにデータを渡す方法
は、このために私のコードです:
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);
}
ありがとう、私はあなたのコードを実装し、私が得たすべてのエラーに取り組んだ、そして今それは本当に動作しています。私はまだ質問があります。インターフェイスで最初のコードブロックを使用したことはありませんでしたが、それはどうしますか? また、私は完全なソリューションを投稿する必要があります他の人のためにここにコードしますか?これは私の最初の質問でした。 – Tyrone3
@ Tyrone3ここをクリックしてください:[インターフェースとは](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html)。まもなくそれは契約であり、クラスはそれを実装すべきです。クラスは多くのコントラクトを実装できます。アクティビティでは、そのインターフェイスの匿名インスタンスを作成しました。私の答えがあなたのニーズに合っていれば、完全な解決策を投稿すべきではありません。あなたの質問/回答をより具体的でなく、幅広い聴衆に適用できるようにしてください。 – Beloo