如何在ViewPager中设置setOnTouchListener

时间:2012-07-01 15:05:12

标签: android android-viewpager

我有一个ViewPager,每个视图有一个ImageView。我需要在视图中为currentItem设置一个OnTouchListener。我有以下代码但在尝试设置监听器时仍然保持NULL。以下是我的代码。如何获得对当前项目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;
        }

1 个答案:

答案 0 :(得分:0)

致电时:

view = inflater.inflate(resId, null);
calendar = (ImageView) findViewById(R.id.imageView1);

它在Activity的contentView中查找ID为R.id.imageView1的ImageView(即:你最初在onCreate()中设置的布局。我认为这不是你想要的。

您可能希望在刚刚充气的视图中找到该视图。试试这个:

view = inflater.inflate(resId, null);
calendar = (ImageView) view.findViewById(R.id.imageView1);