2016-04-05 61 views
0

ImageAdapter如何爲viewpager中的每個幻燈片設置onClickListeners?

public class ImageAdapter extends PagerAdapter implements AdapterView.OnItemClickListener { 
    Context context; 
    private int[] GalImages = new int[] {//array storing all images used in the 'slideshow' in the main menu 
      R.drawable.savedpageex, 
      R.drawable.ic_cdi_icon, 
      R.drawable.savedpageex, 
      R.drawable.ic_cdi_icon 
    }; 

    ImageAdapter(Context context){ 
     this.context=context; 
    } 

    @Override 
    public int getCount() { 
     return GalImages.length; 
    } 

    @Override 
    public boolean isViewFromObject(View view, Object object) { 
     return view == ((ImageView) object); 
    } 

    @Override 
    public Object instantiateItem(ViewGroup container, int position) { 
     ImageView imageView = new ImageView(context); 
     // int padding = context.getResources().getDimensionPixelSize(R.dimen.abc_panel_menu_list_width); 
     imageView.setPadding(1, 1, 1, 1); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
     imageView.setImageResource(GalImages[position]); 
     ((ViewPager) container).addView(imageView, 0); 

     return imageView; 
    } 

    @Override 
    public void destroyItem(ViewGroup container, int position, Object object) { 
     ((ViewPager) container).removeView((ImageView) object); 
    } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     final int clickedImage = GalImages[position]; 
    } 
} 

在MainActivity

ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager); 

ImageAdapter adapter = new ImageAdapter(this); 
wrappedAdapter = new InfinitePagerAdapter(adapter); 
viewPager.setAdapter(wrappedAdapter); 

viewPager.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show(); 
    } 
}); 

眼下,圖片顯示了,他們循環,我需要幫助,在設定的時間間隔獲取圖片「幻燈片」,但主要問題是在每個「頁面」上設置ClickListeners。任何幫助/建議?

+1

您是否嘗試覆蓋''public void onItemClick(AdapterView parent,View view,int position,long id)'方法? –

+0

它尚未被覆蓋? – Michael

回答

0

您可以在onClickListener內添加一個switch語句像這樣

switch(viewPager.getCurrentItem()){ 
    case 0: 
     //stuff for first page 
     break; 
    case 1: 
     //stuff for second page 
     break; 
} 

......等等

或添加一個狀態到viewpager來描述「頁」是顯示 並使用該信息在onClickListener中做不同的事情

+0

我嘗試了你的建議,不幸的是它最終沒有什麼區別(目前它不管我點擊什麼都不會做任何事情,我設置了簡單的Toast消息,當每個按鈕被點擊時彈出,但是當頁面沒有出現時被點擊。 – Michael

相關問題