Martin Erlic
Martin Erlic

Reputation: 5667

PageTitles for Custom ViewPager

The following is my XML, with my PagerTitleStrip embedded into the 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>

And this is my custom PagerAdapter class.

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

Currently, getPageTitle only returns a constant String. How do I return a unique title for each image?

Upvotes: 3

Views: 81

Answers (2)

Martin Erlic
Martin Erlic

Reputation: 5667

Cool. I did it like this:

@Override
    public CharSequence getPageTitle(int position) {
        String[] titlesArray = {
                "Good morning",
                "Good evening",
                "Good night",
        };

        return titlesArray[position];
    }

Upvotes: 0

M D
M D

Reputation: 47817

Do

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

Just get item from ArrayList by using position in getPageTitle(...)

Upvotes: 2

Related Questions