如何在viewpager中设置页码?

时间:2018-12-12 09:01:52

标签: android android-viewpager android-pageradapter

我现在已经创建了viewPager,我想知道如何在viewPager上设置页码?当我从索引页面单击12号时,如何转到viewpager 12号。下面有一张图片。

enter image description here

这是我的代码

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

1 个答案:

答案 0 :(得分:0)

您可以在分页器项目中使用Textview。并从位置设置文本。

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