본문 바로가기

안드로이드

ViewPager2 자동 슬라이드 갤러리

ViewPager2  이용해서...  3초마다 자동 슬라이드 되면서 무한 루핑 되는 갤러리 입니다..

 

build.gradle

implementation "androidx.viewpager2:viewpager2:1.0.0" //뷰페이저2

implementation 'me.relex:circleindicator:2.1.6'  //인디케이터
implementation 'com.github.bumptech.glide:glide:4.12.0'  //이미지 로드 라이브러리

 

GalleryFragment.java

public class GalleryFragment extends Fragment {

ViewPager2 viewPager;

ArrayList<String> imgList = new ArrayList<>();
CircleIndicator indicator;
int firstImageCount=0;



@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

return inflater.inflate(R.layout.view_gallery, container, false);

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

imgList.add("https://www.jeju.go.kr/media/dFU");
imgList.add("https://img1.daumcdn.net/thumb/R720x0.q80/?scode=mtistory2&fname=http%3A%2F%2Fcfile23.uf.tistory.com%2Fimage%2F257AD136585E9F900DB3A2");
imgList.add("https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg/538px-KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg");
imgList.add("https://user-images.githubusercontent.com/14171723/38237327-ea8234e0-3761-11e8-8524-b42d30e8d834.png");


firstImageCount =imgList.size();
viewPager = view.findViewById(R.id.pager_gallery);
viewPager.setAdapter(new GalleryViewPagerAdapter(imgList,getActivity() ,viewPager));


viewPager.setClipToPadding(false);
viewPager.setClipChildren(false);
viewPager.setOffscreenPageLimit(3);


indicator = view.findViewById(R.id.indicator);


float pageMarginPx = getResources().getDimension(R.dimen.pageMargin) ;// dimen 파일 안에 크기를 정의해두었다.
float pagerWidth = getResources().getDimension(R.dimen.pageWidth); // dimen 파일이 없으면 생성해야함
float screenWidth = getResources().getDisplayMetrics().widthPixels ;// 스마트폰의 너비 길이를 가져옴
final float offsetPx = screenWidth - pageMarginPx - pagerWidth;


viewPager.setPageTransformer((page, position) -> {
float myOffset = position * -offsetPx;

if (position < -1) {
page.setTranslationX(-myOffset);


} else if (position <= 1) {
float scaleFactor = Math.max(0.7f, 1 - Math.abs(position - 0.14285715f)) ;
page.setTranslationX(myOffset) ;

page.setScaleY(scaleFactor);
page.setAlpha(scaleFactor);



}else{
page.setAlpha(0f) ;
page.setTranslationX(myOffset);

}


});





viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
headerHandler.removeCallbacks(headerRunnable);
headerHandler.postDelayed(headerRunnable, 3000); // Slide duration 3 seconds

indicator.animatePageSelected(position%firstImageCount);



}
});

initIndicaotor();

}

private void initIndicaotor(){
indicator.createIndicators(imgList.size(),0);


}

private Handler headerHandler = new Handler();

private Runnable headerRunnable = new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);

}
};

@Override
public void onPause() {
super.onPause();
headerHandler.removeCallbacks(headerRunnable);
}

@Override
public void onResume() {
super.onResume();
headerHandler.postDelayed(headerRunnable, 3000); // Slide duration 3 seconds
}


}

 

 

GalleryViewPagerAdapter.java

public class GalleryViewPagerAdapter extends RecyclerView.Adapter<GalleryViewPagerAdapter.ViewHolderPage> {

private ArrayList<String> listData;
Context con;
ViewPager2 pager;

public GalleryViewPagerAdapter(ArrayList<String> data , Context con , ViewPager2 pager) {
this.listData = data;
this.pager = pager;
this.con =con;
}

@Override
public ViewHolderPage onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.item_viewpager, parent, false);
return new ViewHolderPage(view);
}


@Override
public void onBindViewHolder(ViewHolderPage holder, int position) {
if(holder instanceof ViewHolderPage){
// position = position%listData.size();

ViewHolderPage viewHolder = (ViewHolderPage) holder;
viewHolder.onBind(listData.get(position));

if (position == listData.size() - 2) {
pager.post(runnable);
}
}
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
listData.addAll(listData);
notifyDataSetChanged();
}
};

@Override
public int getItemCount() {
return listData.size();
}

public class ViewHolderPage extends RecyclerView.ViewHolder {

private ImageView img;
private RelativeLayout rl_layout;
String data;



ViewHolderPage(View itemView) {
super(itemView);

img = itemView.findViewById(R.id.img);


}

public void onBind(String data){
this.data = data;
Glide.with(con).load(data).into(img);

}
}
}

 

 

view_gallery.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:gravity="center"
>


<androidx.viewpager2.widget.ViewPager2 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager_gallery"
android:layout_width="match_parent" android:clipToPadding="false"
android:clipChildren="false"
android:layout_height="300dp"
/>

<me.relex.circleindicator.CircleIndicator
android:id="@+id/indicator"
android:layout_width="match_parent" app:ci_drawable="@color/black" app:ci_drawable_unselected="@color/gray"
android:layout_height="40dp"/>


</androidx.appcompat.widget.LinearLayoutCompat>

 

 

item_viewpager.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_layout"
android:layout_width="match_parent" android:gravity="center"
android:layout_height="match_parent">

<ImageView
android:id="@+id/img"
android:layout_width="300dp" android:scaleType="centerCrop"
android:layout_height="300dp"
/>
</LinearLayout>

 

 

 

dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="pageMargin">20dp</dimen>
<dimen name="pageWidth">300dp</dimen>

</resources>