Kuwame Brown
Kuwame Brown

Reputation: 533

Implementing onClickListener to ViewPager

pager.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {  

public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}

public void startUpdate(View container) {
}
}
}

Upvotes: 3

Views: 16230

Answers (1)

sleep
sleep

Reputation: 4944

Set the listener on the image inside instantiateItem():

        @Override
        public Object instantiateItem(View collection, int position) {
            final LayoutInflater inflater = getLayoutInflater(); 
            View layout = inflater.inflate(R.layout.my_layout, null);
            final ImageView image = (ImageView)layout.findViewById(R.id.image_display);
            final int cPos = position;
            image.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    ImageView i = (ImageView)v;
                    if(cPos == 0)
                    {
                        //...
                    }
                    //...

                }
            });

            return layout;
        }

Alternatively, you could use the ImageView.setTag() method to include data about what Activity to launch. e.g.

if(position == 0) image.setTag("com.blah.android.SomeActivity");
if(position == 1) image.setTag("com.blah.android.AnotherActivity");
//...

And the inside the onClick() above have this instead:

ImageView i = (ImageView)v;
String activityClassName = (String)i.getTag();   // Get the info we stored in the tag.
MyActivity.this.startActivity((new Intent()).setClassName(MyActivity.this, activityClassName));

Note that here you don't actually need the cast to ImageView, since getTag() is a method of View. You also don't need a separate OnClickListener for each ImageView. You could just create a single instance of an OnClickListener that grabs the tag data as above, and launches the appropriate activity. Set this OnClickListener on every ImageView inside instantiateItem().

P.S. I strongly recommend, if you are downloading images, that you look at some of the image downloaders that have been written for Android. e.g. https://github.com/nostra13/Android-Universal-Image-Loader

Upvotes: 19

Related Questions