I have a horizontalscrollview inside which i have a bunch of images. Now i need to detect the click event in case any of the image is clicked within it. In short, i need the index of the image placed inside the horizontalscrollview, which was clicked.
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bgcolor" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:src="@drawable/image1" />
<ImageView
android:id="@+id/imageview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:src="@drawable/image2" />
I tried playing around OnTouchListener event, but that was getting triggered even while scrolling. And the OnClickListener was not even getting triggered no matter wherever you click.
horizontalScrollView1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("Testing scrollview");
}
});
Is there a workaround to get the index of the clicked image present inside the horizontalscrollview? I guess it can be achieved via "Gallery" widget but that is deprecated in API16. Can anyone share an approach to accomplish this via HorizontalScrollView?
I assume the number of ImageViews may vary in your case. Then I would suggest using a List of IDs to keep record of them. While inserting new ImageView to HorizontalScrollView, use setId method to add each ImageView a custom ID and then add this ID to your List.
If the number of ImageViews is fixed, then you can of course use classic array:
Then your onClick method (you have to add it to each ImageView) will look like this:
EDIT: how to create valid IDs - Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Attach an
OnClickListener
to each of theImageView
widgets in theHorizontalScrollView
. Based on theView
passed intoonClick()
, you will know whichImageView
was clicked.Specifically:
Add
android:onClick="heyMyImageGotClickedWhoHoo"
to eachImageView
element in your layout.Implement a
public void heyMyImageGotClickedWhoHoo(View v)
method in the activity that is loading this layout. In the body, you can usev.getId()
and compare it to theImageView
widget IDs (e.g.,R.id.imageview1
) to determine which got clicked.Or, you can create dedicated methods for each
ImageView
, rather than route them all to one. In that case, eachandroid:onClick
attribute would have a different value (e.g.,omgTheFirstImageWasClicked
), with a matching method in the activity (e.g.,public void omgTheFirstImageWasClicked(View v)
).