1

我正在尝试从一组图像中做一个简单的 ViewPager 。

我的数组是:

<string-array name="ot_images">
   <item>"file:///android_res/drawable/ot_100.jpg"</item> 
   <item>"file:///android_res/drawable/ot_101.jpg"</item> 
   <item>"file:///android_res/drawable/ot_102.jpg"</item> 
   <item>"file:///android_res/drawable/ot_103.jpg"</item> 

我的布局是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<ImageView
    android:id="@+id/iView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

</RelativeLayout>

到目前为止 MyPagerAdapter.java

public class MyPagerAdapter extends PagerAdapter{

public int getCount() {
    return 5;
}

public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    int resId = 0;
    switch (position) {
    case 0:
        resId = R.layout.farleft;
        break;
    case 1:
        resId = R.layout.left;
        break;
    case 2:
        resId = R.layout.middle;
        break;
    case 3:
        resId = R.layout.right;
        break;
    case 4:
        resId = R.layout.farright;
        break;
    }
    View view = inflater.inflate(resId, null);
    ((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;
}
}

我遵循了本教程: Android 用户界面设计:水平视图分页

一切正常,但我的问题是:

您如何使用 1 个布局而不是 5 个布局的本教程?谢谢!

4

1 回答 1

1

您只需要定义一个通用布局,并通过覆盖该方法common_layout.xml将其放置在 viewpager 的容器中。instantiateItem在下面的示例中,我假设您有一个带有 id 文本的 TextView。

public Object instantiateItem(View collection, int position) {

   LayoutInflater inflater = (LayoutInflater) collection.getContext()
                   .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View view = inflater.inflate(R.layout.common_layout, null);
   switch (position) {
       case 0:
         ((TextView)view.findViewById(R.id.text)).setText("One");
         break;
       case 1:
         ((TextView)view.findViewById(R.id.text)).setText("Two");
         break;
       case 2:
         ((TextView)view.findViewById(R.id.text)).setText("Three");
         break;
       case 3:
         ((TextView)view.findViewById(R.id.text)).setText("Four");
         break;
       case 4:
         ((TextView)view.findViewById(R.id.text)).setText("Five");
         break
     }

    ((ViewPager) collection).addView(view, 0);
    return view;
 }
于 2013-06-19T12:03:37.513 回答