Click event of HorizontalScrollView

本小妞迷上赌 提交于 2019-12-06 14:39:53

Attach an OnClickListener to each of the ImageView widgets in the HorizontalScrollView. Based on the View passed into onClick(), you will know which ImageView was clicked.

Specifically:

  • Add android:onClick="heyMyImageGotClickedWhoHoo" to each ImageView 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 use v.getId() and compare it to the ImageView 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, each android:onClick attribute would have a different value (e.g., omgTheFirstImageWasClicked), with a matching method in the activity (e.g., public void omgTheFirstImageWasClicked(View v)).

daemontus

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.

int uniqueID = getNewID();
myImage.setId(uniqueID);
myIdList.add(uniqueID);
myScrollView.addView(myImage);

If the number of ImageViews is fixed, then you can of course use classic array:

int[] ids = {R.id.firstImage, R.id.secondImage};

Then your onClick method (you have to add it to each ImageView) will look like this:

public void onClick(View v) {
    for(int i=0; i<ids.size(); i++) {
        if(v.getId() == ids.get(i)) {
            Toast.makeText(this, "Index "+(i+1), Toast.LENGTH_SHORT).show();
        }
    }
}

EDIT: how to create valid IDs - Android: View.setID(int id) programmatically - how to avoid ID conflicts?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!