2016-11-18 150 views
0

在我的活動中,我有一個OnPageChangeListener和查看傳呼機實現。viewPager不刷新instantiateItem

論功能onPageSelected我調用函數名viewPagerHandler,當我把所有的邏輯單viewPager頁(按鈕,操作取決於當前頁面等)

public class ActivityClass extends Activity implements ViewPager.OnPageChangeListener, View.OnClickListener{ 

    protected void onCreate(Bundle savedInstanceState) { 
    viewPager=(ViewPager)findViewById(R.id.Pager); 
      adapter= new 
    ViewPageAdapter(ActivityClass.this,list,imagesList); 
      viewPager.setAdapter(adapter); 
       viewPager.setCurrentItem(0); 
      viewPager.addOnPageChangeListener(ActivityClass.this); 
    } 

    @Override 
     public void onClick(View v) { 
     } 

     @Override 
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

     } 
     @Override 
     public void onPageSelected(int position) { 
      this.position=position; 
      viewPagerHandler(viewPager.findViewWithTag(position),position); 
     } 

     @Override 
     public void onPageScrollStateChanged(int state) { 
     } 
    public View viewPagerHandler(final View view, final int position){ 
    //ALL LOGIC BUTTONS ACTIONS ETC. 
    view.invalidate(); 
    return view; 
    } 
     } 
    public class ViewPageAdapter extends PagerAdapter{ 

    @Override 
     public Object instantiateItem(final ViewGroup container, final int position) { 
      final View itemView = LayoutInflater.from(mContext).inflate(R.layout.art_work_item, container, false); 
      itemView.setTag(position); 

container.add(itemView); // edited after suggested 
      if(mContext instanceof ActivityClass && position==0) //The page listener in ActivityClass is trigger only when page is changed so i tried to hack it when the viewPager is instantiate for the first time    
return ((ActivityClass) mContext).viewPagerHandler(itemView,position); 

      return itemView; 
     } 
    } 

編輯:邏輯完美的作品上第一個和最後一個項目。對於其他人來說,視圖並不令人耳目一新(不過它仍然有效,因爲我點擊了按鈕後顏色發生了變化,當我點擊它們,然後滑動到下一個項目並返回到前一個顏色時,顏色被更改爲觸發器)

回答

1

你缺少在instantiateItem()方法行,

public Object instantiateItem(final ViewGroup container, final int position) { 
    final View itemView = LayoutInflater.from(mContext).inflate(R.layout.art_work_item, container, false); 
    itemView.setTag(position); 

    container.addView(itemView); 

    if(mContext instanceof ActivityClass && position==0) //The page listener in ActivityClass //is trigger only when page is changed so i tried to hack it when the viewPager is //instantiate for the first time 
    return ((ActivityClass) mContext).viewPagerHandler(itemView,position); 

    return itemView; 
} 
+0

所以我應該返回容器我instantiateItem? – Expiredmind

+0

@Expiredmind不返回itemView,但添加到容器 – Raghavendra

+0

沒有隻是在返回語句前添加此行 –