In my XML file I have layout for my fragment which contains HorizontalScrollView
like this:
<HorizontalScrollView
android:id="@+id/srollview_seasons_gallery
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left">
</HorizontalScrollView>
In separate XML file called season_list_item
I've made a schema how single item should look like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/season_image"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:onClick="seasonItemClicked"/>
</RelativeLayout>
I add items dynamically with my java code like this:
for (int i=0; i<seasonsSize; i++) {
View vi = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.season_list_item, null);
ImageView seasonImage = (ImageView) vi.findViewById(R.id.season_image);
//seasonImage.setId(i);
String imgUrl = response.body().getEmbedded().getSeasons().get(i).getImage().getMedium();
Picasso.with(getContext()).load(imgUrl).into(seasonImage);
seasonsLinearLayout.addView(vi);
}
seasonsScrollView.addView(seasonsLinearLayout);
And when I execute my onClick method:
public void seasonItemClicked(View view) {
}
I get error
java.lang.IllegalStateException: Could not find method seasonItemClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageView with id 'season_image'
Uncommenting this line //seasonImage.setId(i);
gives me error
android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0`
Pictures are added to layout correctly, just like I want them to. But I cannot achieve to make them clickable. I also find seasonImage.setId(i)
important in my case since I need number of the picture that was clicked for further actions.
Could you help me out how this should be approached?
The problem is
android:onClick
which call your methodseasonItemClicked()
. As many views you have with this attribute, they will all call this same method, but with the same IDandroid:id="@+id/season_image"
.The
setId
method could be very annoying because you have to set an unique id. There is some method to generate it, so, for each image, you have to generate an unique ID, and if you set it dynamically, don't set it by xml.However, assuming that your number of images can be variable, I'd prefer to add the click listener programmatically in the for-loop. That way, they will be related to the imageview clicked. As follows:
And just remove the
android:onclick
attribute: