2012-07-01 57 views
0

我有一個ViewPager,每個ViewView有一個ImageView。我需要在視圖中爲currentItem設置一個OnTouchListener。我有以下代碼,但在嘗試設置偵聽器時仍保持NULL。以下是我的代碼。我怎樣才能得到我的當前項目ImageView的有效參考?如何在ViewPager中設置setOnTouchListener

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; 
     } 

回答

0

當你撥打:

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

它會在您的活動的內容查看與ID R.id.imageView1的ImageView的(即:您原來在的onCreate設置佈局()。我認爲是不是你想要的

你可能想找到你剛纔充氣視圖的視圖試試這個:。

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

就是這樣,我的菜鳥錯誤。 – Byron

相關問題