I have a custom ListView that display song titles and each one contains two ImageView for adding to favorites and sharing song.
custom_listview.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="@+id/song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/add_to_favorites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
To fill the listview I need to use an ArrayAdapter:
public class Media_adapter extends ArrayAdapter<Media> {
Context context;
int layoutResourceId;
Media data[] = null;
public Media_adapter(Context context, int layoutResourceId, Media[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MediaHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MediaHolder();
holder.song_title = (TextView)row.findViewById(R.id.song_title);
holder.add_to_favorites = (ImageView)row.findViewById(R.id.add_to_favorites);
holder.share = (ImageView)row.findViewById(R.id.share);
row.setTag(holder);
}
else
{
holder = (MediaHolder)row.getTag();
}
Media media = data[position];
holder.song_title.setText(media.title);
holder.add_to_favorites.setImageResource(media.image_favorite);
holder.share.setImageResource(media.image_share);
return row;
}
class MediaHolder
{
TextView song_title;
ImageView add_to_favorites, share;
}
}
Class Media:
package com...;
public class Media {
public String title;
public int image_favorite, image_share;
public Media() {
super();
}
}
To playing a song, I have called setOnItemClickListener(...)
mylistview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av,
View view, int position, long l) {
//code for playing song
}
});
Finally, I want to add onClick event for my two ImageView add_to_favorites
and share
used in item of Listview.