androidandroid-viewpagerandroid-pageradapter

How can I set page numbers in viewpager?


I've created viewPager now I want to know that how can I set page numbers on viewPager? And how can i go to viewpager number 12 when I click on 12 number from index page. Below there is an image .

enter image description here

Here is my code

public class SwipeAdapter extends PagerAdapter {
private Context cx;
int[] image=new int[3];
int a=1;
SwipeAdapter(Context cx){
    this.cx=cx;
    for(int i=0;i<3;i++) {
        a = i + 1;

        image[i]=cx.getResources().getIdentifier("image"+a,"drawable", cx.getPackageName());
}
}
@Override
public int getCount() {
    return image.length;
}

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

@SuppressLint("SetTextI18n")
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {

    LayoutInflater layoutInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    assert layoutInflater != null;
    View view= layoutInflater.inflate(R.layout.fragment_page,container,false);
    ImageView imageView= view.findViewById(R.id.imageView);
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    imageView.setImageResource(image[position]);
    container.addView(view);
    return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((RelativeLayout) object);
}

Solution

  • You can take Textview in pager item. and set text from position.

    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        LayoutInflater layoutInflater = (LayoutInflater) cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert layoutInflater != null;
        View view = layoutInflater.inflate(R.layout.fragment_page, container, false);
        ImageView imageView = view.findViewById(R.id.imageView);
    
        TextView text = view.findViewById(R.id.textView);
        text.setText(String.valueOf(position + 1);
    
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageResource(image[position]);
        container.addView(view);
        return view;
    }