在Picasso和Viewpager制作的滑块图像中添加下一个,上一个按钮

时间:2019-06-25 07:49:24

标签: java android android-viewpager picasso android-button

我已经在viewpager和毕加索的帮助下制作了一个图像滑块,现在我想在图像上添加下一个,上一个按钮,该怎么做?

我看到了不同的答案,但是所有人都显示出错误

这是显示图像滑块的主要活动:

public class MainActivity extends AppCompatActivity {
    private int[] imageUrls = new int[]{
            R.drawable.after_cookie,
            R.drawable.before_cookie
    };
    private WebBackForwardList viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = findViewById(R.id.view_pager);
        ViewPageAdapter adapter = new ViewPageAdapter(this, imageUrls);
        viewPager.setAdapter(adapter);

    }
}

这是ViewPageAdapter:

public class ViewPageAdapter extends PagerAdapter {

    private Context context;
    private int[] imageUrls;

    ViewPageAdapter(Context context, int[] imageUrls) {
        this.context = context;
        this.imageUrls = imageUrls;
    }



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

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

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(context);
        Picasso.get()
                .load(imageUrls[position])
                .fit()
                .centerCrop()
                .into(imageView);
        container.addView(imageView);

        return imageView;
    }

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

1 个答案:

答案 0 :(得分:0)

将此方法添加到您的代码中

private int getItem(int i) {
   return viewPager.getCurrentItem() + i;
}

然后将其用于下一个按钮

Button NextButton = (Button)findViewById(R.id.button1);
yourButton.setOnClickListener(new OnClickListener() {

 @Override
       public void onClick(View view) {
           viewPager.setCurrentItem(getItem(+1), true); //getItem(+1) for next
       }
    });

并将其用于上一个按钮

 Button PreviousButton = (Button)findViewById(R.id.button2);
 PreviousButton.setOnClickListener(new OnClickListener() {

 @Override
       public void onClick(View view) {
           viewPager.setCurrentItem(getItem(-1), true); //getItem(-1) for previous
       }
    });

它将正常工作;)