我使用viewpager类来显示图像集而不是gallery类,因为它已弃用并使用以下代码对其进行自定义以显示文本,问题是所有图像都显示相同的文本,我试图得到的是: 不同的文本每张解释它的图像,假设我们有 5 张图像,它必须有 5 种不同的文字,每个文字都描述它的图像。
任何建议将不胜感激,谢谢
编码:
图像寻呼机
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}; }
图像页面适配器
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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/myimagepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
custom_pager.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FFDAB9"
android:gravity="center_horizontal">
<ImageView android:id="@+id/myimage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="2" />
<TextView android:id="@+id/image_text"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:textColor="#B22222"
android:layout_weight="1"
android:text="text to image" />
</LinearLayout>