使用视图适配器类滑动图像

时间:2013-12-08 18:17:28

标签: android image view swipe adaptor

我尝试将图像及其文本和tts一起滑动。我使用过ViewPageAdapter。 代码是

public class ViewPagerAdapter extends PagerAdapter{

Activity activity;
int imageArray[];
String[] arrToDisplay;

public ViewPagerAdapter(Activity act, int[] imgArra, String[] arrayObject) {
    imageArray = imgArra;
    activity = act;
    arrToDisplay = arrayObject;

  }

public int getCount() {
    return imageArray.length;
}



public Object instantiateItem(View collection, int position) {
    ImageView view = new ImageView(activity);

    view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT));
    view.setScaleType(ScaleType.FIT_XY);
    view.setBackgroundResource(imageArray[position]);
    ((ViewPager) collection).addView(view, 0);
    return view;
  }


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


}

的xml:

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:orientation="vertical" >

    <!--ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/a_elephant" /-->

    <android.support.v4.view.ViewPager
        android:id="@+id/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="494dp" />

</LinearLayout>

Main.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

           ViewPagerAdapter adapter = new ViewPagerAdapter(this, arrAnimals1, arrAnimals);
    ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);


}

以上代码正确滑动图像。问题是我想和tts一起显示文本。我试过这段代码在适配器类中显示文本,但它不起作用:

public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService
             (Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.animals, null);

    ImageView im=(ImageView) layout.findViewById(R.id.imageView1);
    im.setBackgroundResource(imageArray[position]);
    TextView dsc=(TextView) layout.findViewById(R.id.txtObjName);
    dsc.setText("asdfasdf");
    ((ViewPager) collection).addView(layout, 0);
    return layout; 
}

请帮忙。

谢谢, 编辑

1 个答案:

答案 0 :(得分:0)

我建议您使用FragmentStatePagerAdapterFragmentPagerAdapter。这些适配器的getItem()返回Fragment;您可以为包含FragmentImageView

TextView创建xml