Since the onClick event is never triggered on a ViewPager
(see this question), I'm going to set the onClickListener
to the item container in the adapter.
The idea is, when an item is clicked, to call from the adapter a method from the Fragment in which this adapter is set to the ViewPager
.
For an Activity
I would pass the context and call the method using this context (something like ((myActivity)context).itemContainerOnClick()
).
But how can I do with a Fragment? Could I face any issue passing the Fragment as an argument to my adapter's constructor?
Thanks
Fragment
public class MyFragment extends Fragment {
ViewPager mViewPager;
int mPosition = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (RelativeLayout) inflater.inflate(R.layout.my_fragment_container, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new MyAdapter(getActivity(), myObjectArray);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mPosition = position;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageScrollStateChanged(int state) {}
});
mViewPager.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// I want to start some activity, passing mPosition
// but this is never called
}
});
return view;
}
// Alternative to mViewPager.setOnClickListener, called from the adapter
public void onViewPagerClick()
{
// start some activity, passing mPosition
}
}
PageAdapter
class MyAdapter extends PagerAdapter {
private MyObject[] mItemArray;
private Context mContext;
public SejoursWidgetAdapter(Context context, MyObject[] itemArray) {
mContext = context;
mItemArray = itemArray;
}
@Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item, null);
// Add click listener here because setting it directly on the ViewPager does not work (onClick not triggered)
row.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// How can I call MyFragment's onViewPagerClick() ?
}
});
((ViewPager) collection).addView(row);
return row;
}
/* More stuff */
}