图像viewpager中每个图像的不同文本

我使用viewpager类来显示图像集而不是图库类,因为它已弃用并自定义它以使用下面的代码显示文本,问题是所有图像显示的文本相同,我试图得到的是: 不同的文本解释它的每个图像 ,假设我们有5个图像,它必须有5个不同的文本,每个图像描述它的图像。

任何建议将不胜感激,谢谢

代码:

ImagePager

public class ImagePager extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra); ViewPager myPager = (ViewPager) findViewById(R.id.myimagepager); myPager.setAdapter(adapter); myPager.setCurrentItem(0);} private int imageArra[] = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e}; } 

ImagePagerAdapter

  public class ImagePagerAdapter extends PagerAdapter { Activity activity; int imageArray[]; public ImagePagerAdapter(Activity act, int[] imgArra) { imageArray = imgArra; activity = act;} public int getCount() { return imageArray.length;} public Object instantiateItem(View collection, int position) { LayoutInflater inflater = (LayoutInflater)collection.getContext ().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_pager, null); ImageView im=(ImageView) layout.findViewById(R.id.myimage); im.setImageResource(imageArray[position]); TextView txt=(TextView) layout.findViewById(R.id.image_text); ((ViewPager) collection).addView(layout, 0); return layout; } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); } @Override public Parcelable saveState() { return null; } } 

activity_main.xml中

    

custom_pager.xml

     

您可以将一个字符串数组传递到适配器中,该数组对应于每个图像。

在活动中使用您的图像列表声明您的字符串数组。

 private int imageArra[] = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e}; private String[] stringArray = new String[] { "Image a", "Image b","Image c","Image d","Image e"}; 

然后在实例化你的适配器..

 ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra, stringArray ); 

在您的适配器中:

 int imageArray[]; String[] stringArray; public ImagePagerAdapter(Activity act, int[] imgArra, String[] stringArra) { imageArray = imgArra; activity = act; stringArray = stringArra; } 

然后从数组中分配文本值

 TextView txt=(TextView) layout.findViewById(R.id.image_text); txt.setText(stringArray[position]);