以下是我的XML,并将我的PagerTitleStrip嵌入到ViewPager中:

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:scaleType="centerCrop">

        <android.support.v4.view.PagerTitleStrip
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:layout_gravity="top" />

    </android.support.v4.view.ViewPager>

这是我的自定义PagerAdapter类。
public class CustomPagerAdapter extends PagerAdapter {

    private int[] image_resources = {
            R.drawable.1,
            R.drawable.2,
            R.drawable.3
    };
    private Context ctx;
    private LayoutInflater layoutInflater;
    public CustomPagerAdapter(Context ctx) {
        this.ctx = ctx;
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return "Title Here";
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.pager_item, container, false);
        ImageView imageview = (ImageView) item_view.findViewById(R.id.image_view);
        imageview.setImageResource(image_resources[position]);
        container.addView(item_view);
        return item_view;
    }

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

当前,getPageTitle仅返回常量String。如何为每个图像返回唯一的标题?

最佳答案


@Override
public CharSequence getPageTitle(int position) {
    return "Page: "+position;
}

只需使用item中的位置ArrayList中获取getPageTitle(...)

09-08 02:12