I have a ViewPager that has one ImageView per view. I need to setup an OnTouchListener for the currentItem in the view. I have the following code but keep getting NULL when I try and setup the listener. Below is my code. How can I get a valid reference to my current items ImageView???
private class CalendarPagerAdapter extends PagerAdapter {
public int getCount() {
return NUM_VIEW;
}
public Object instantiateItem(View collection, int position) {
View view=null;
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.cal_july;
view = inflater.inflate(resId, null);
calendar = (ImageView) findViewById(R.id.imageView1);
// IT IS ALWAYS NULL HERE
if(calendar == null) {
System.out.println("its null!!!!!!");
} else {
System.out.println("its NOT NULL!!!!!");
}
// Breaks here, obviously!!!
calendar.setOnTouchListener(getOnTouchListener());
break;
case 1:
resId = R.layout.cal_august;
view = inflater.inflate(resId, null);
calendar = (ImageView) findViewById(R.id.imageView1);
calendar.setOnTouchListener(getOnTouchListener());
break;
case 2:
resId = R.layout.cal_september;
break;
case 3:
resId = R.layout.cal_october;
break;
case 4:
resId = R.layout.cal_november;
break;
}
((ViewPager) collection).addView(view, 0);
return view;
}
When you call:
it looks for the ImageView with the ID R.id.imageView1 in your Activity’s contentView (ie: the layout that you originally set in your onCreate(). I assume that isn’t what you want.
You probably want to find the view in the view you just inflated. Try this: