본문 바로가기
안드로이드 자바

[JAVA][Android] ViewPager2 사용하여 슬라이드 화면 만들기

by teamnova 2021. 10. 2.
728x90

안녕하세요

 

오늘은 ViewPager2를 사용하여 슬라이드 화면을 만들어보겠습니다.

 

우리가 흔히 사용하는 스와이프로 화면 넘기기기능입니다.

 

스와이프란 손가락으로 화면을 터치하여 직선으로 움직였을 때 다른 화면으로 넘어가는 것을 뜻합니다.

 

 

*결과

 

먼저 아래 스틱코드 링크에서 즐겨찾기 추가를 해주세요

https://stickode.com/detail.html?no=2491 

 

스틱코드

 

stickode.com

 


 

들어가기에 앞서

매니페스트에 아래 코드를 추가해주세요

 

    <uses-permission android:name="android.permission.INTERNET" />

 

build.gradle(app)에서 아래 코드를 추가해주세요

 

    // ViewPager2
    implementation "androidx.viewpager2:viewpager2:1.0.0"

    // Glide
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

 


viewpager2 태그를 입력하면 스틱코드 탭이 생성되고 

 

탭을 클릭하여 해당 코드를 가져옵니다.

 

1. MainAcitivity.java

 

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.viewpaper2.R;



public class MainActivity extends AppCompatActivity {

    private ViewPager2 sliderViewPager;
    private LinearLayout layoutIndicator;

    private String[] images = new String[] {
            "https://cdn.pixabay.com/photo/2018/01/15/08/34/woman-3083453_960_720.jpg",
            "https://cdn.pixabay.com/photo/2021/06/28/18/36/cereals-6372410_960_720.jpg",
            "https://cdn.pixabay.com/photo/2021/07/15/17/55/fishermans-bastion-6469128_960_720.jpg",
            "https://cdn.pixabay.com/photo/2021/07/22/01/01/parrot-6484206_960_720.jpg"
    };

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

        sliderViewPager = findViewById(R.id.sliderViewPager);
        layoutIndicator = findViewById(R.id.layoutIndicators);

        sliderViewPager.setOffscreenPageLimit(1);
        sliderViewPager.setAdapter(new ImageSliderAdapter(this, images));

        sliderViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setCurrentIndicator(position);
            }
        });

        setupIndicators(images.length);
    }

    private void setupIndicators(int count) {
        ImageView[] indicators = new ImageView[count];
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        params.setMargins(16, 8, 16, 8);

        for (int i = 0; i < indicators.length; i++) {
            indicators[i] = new ImageView(this);
            indicators[i].setImageDrawable(ContextCompat.getDrawable(this,
                    R.drawable.bg_indicator_inactive));
            indicators[i].setLayoutParams(params);
            layoutIndicator.addView(indicators[i]);
        }
        setCurrentIndicator(0);
    }

    private void setCurrentIndicator(int position) {
        int childCount = layoutIndicator.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ImageView imageView = (ImageView) layoutIndicator.getChildAt(i);
            if (i == position) {
                imageView.setImageDrawable(ContextCompat.getDrawable(
                        this,
                        R.drawable.bg_indicator_active
                ));
            } else {
                imageView.setImageDrawable(ContextCompat.getDrawable(
                        this,
                        R.drawable.bg_indicator_inactive
                ));
            }
        }
    }
}

 

2. activity_main.xml

 

 

3. ImageSliderAdapter.java

 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.viewpaper2.R;


public class ImageSliderAdapter extends RecyclerView.Adapter<ImageSliderAdapter.MyViewHolder> {
    private Context context;
    private String[] sliderImage;

    public ImageSliderAdapter(Context context, String[] sliderImage) {
        this.context = context;
        this.sliderImage = sliderImage;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_slider, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.bindSliderImage(sliderImage[position]);
    }

    @Override
    public int getItemCount() {
        return sliderImage.length;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView mImageView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.imageSlider);
        }

        public void bindSliderImage(String imageURL) {
            Glide.with(context)
                    .load(imageURL)
                    .into(mImageView);
        }
    }
}

 

4. ItemSlider_xml

 

 

5. bgFadingEdge_xml

 

 

6. bgIndicatorActive_xml

 

 

7. bgIndicatorInActive_xml