뷰페이저2 자바로 구현한 예제

xeant 2021.06.14 15:30 조회 수 : 10

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:attrs="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/my_intro_view_pager"
        android:layout_centerInParent="true"
        />

    <ImageView
        android:id="@+id/next_btn"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/ic_right"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:textStyle="bold"
        android:onClick="next_action"
        />
    <ImageView
        android:id="@+id/previous_btn"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/ic_left"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:textStyle="bold"
        android:onClick="pre_action"
        tools:ignore="OnClick" />

    <com.tbuonomo.viewpagerdotsindicator.DotsIndicator
        android:id="@+id/dots_indicator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:dotsColor="#F1F1F1"
        app:dotsCornerRadius="8dp"
        app:dotsSize="16dp"
        app:dotsSpacing="4dp"
        app:dotsWidthFactor="2.5"
        app:selectedDotColor="#FFC107"
        app:progressMode="true"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="60dp"
        />
</RelativeLayout>

activity_main.xm

ViewPager2로 구성된 슬라이드 페이지 
 
 
// Adapter 클래스는 Viewholder 객체를 생성하고, 데이터와 Viewholder 를 결합해서, 화면으로 뿌려주는 역할을 담당
public class MyIntroPagerRecyclerAdapter extends RecyclerView.Adapter<MyIntroPagerViewHolder>{
    private ArrayList<PageItem> mPageItems;
    private Context mContext;
    private static String TAG = "XEANT ";
    public MyIntroPagerRecyclerAdapter(Context context, ArrayList<PageItem> mPageItems) {
        this.mPageItems = mPageItems;
        this.mContext = context;
    }

    // ViewHolder 객체 생성후 생성된 객체를 리턴
    @NonNull
    @Override
    public MyIntroPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_intro_pager_item, parent, false);
        return new MyIntroPagerViewHolder(view);
    }

    // 페이지 넘길때, 발생하는 이벤트
    @Override
    public void onBindViewHolder(@NonNull MyIntroPagerViewHolder holder, int position) {
        // 데이터와 뷰를 묶는다
        Log.d(TAG, "onBindViewHOlder 실행"+ position);
//        PageItem pageItem = mPageItems.get(position);
        holder.bindWithView(mPageItems.get(position));
    }

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

MyIntroPagerRecyclerAdapter.java

   리사이클 어댑터 설정하는 소스코드

 

public class MyIntroPagerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private ImageView itemImage;
    private LinearLayout itemBg;
    private TextView itemContent;
    private static String TAG = "XEANT";
//    pager_item_bg

    public MyIntroPagerViewHolder(@NonNull View itemView) {
        super(itemView);
        itemImage = itemView.findViewById(R.id.pager_item_image);
        itemContent = itemView.findViewById(R.id.pager_item_text);
        itemBg = itemView.findViewById(R.id.pager_item_bg);

        itemView.setOnClickListener(this);
    }
    public void bindWithView(PageItem pageItem){
        Log.d(TAG, pageItem.getBgColor().toString());
        Log.d(TAG, "변경 발생!");
        itemImage.setImageResource(pageItem.getImageSrc());
        itemContent.setText(pageItem.getContent());
        itemBg.setBackgroundColor(pageItem.getBgColor());

        if(pageItem.getBgColor() != R.color.colorWhite){
            itemContent.setTextColor(Color.WHITE);
        }
    }

    @Override
    public void onClick(View v) {
       Log.d("XEANT " , "Click This ITEM" + v.toString());
    }
}

MyIntroPagerViewHolder.java

ViewHolder 설정

 

public class PageItem {
    private Integer bgColor;
    private Integer imageSrc;
    private String content;

    public PageItem(Integer bgColor, Integer imageSrc, String content) {
        this.bgColor = bgColor;
        this.imageSrc = imageSrc;
        this.content = content;
    }

    @Override
    public String toString() {
        return "PageItem{" +
                "bgColor=" + bgColor +
                ", imageSrc=" + imageSrc +
                ", content=" + content +
                '}';
    }

    public Integer getBgColor() {
        return bgColor;
    }

    public void setBgColor(Integer bgColor) {
        this.bgColor = bgColor;
    }

    public Integer getImageSrc() {
        return imageSrc;
    }

    public void setImageSrc(Integer imageSrc) {
        this.imageSrc = imageSrc;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

PageItem.java

PageItem 객체 정의 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:background="@color/colorBlue"
    android:id="@+id/pager_item_bg">

    <ImageView
        android:id="@+id/pager_item_image"
        android:layout_width="350dp"
        android:layout_height="350dp"
        android:layout_marginTop="90dp"
        android:layout_marginBottom="20dp"
        />

    <TextView
        android:id="@+id/pager_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="뷰페이저 아이템 레이아웃"
        android:textSize="30sp"
        android:textAlignment="center"
        />
</LinearLayout>
layout_intro_pager_item.xml

 돌아가게 되는 뷰 페이저 아이템 레이아웃 (MainActivity 에서 각 요소들이 변경되고, 순환되게 된다 

 

 

 

public class MainActivity extends AppCompatActivity {

    private ArrayList<PageItem>  pageItemList;
    private ViewPager2 mRecyclerView;
    private MyIntroPagerRecyclerAdapter my_recycler_adapter;
    private DotsIndicator dotsIndicator ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (ViewPager2) findViewById(R.id.my_intro_view_pager);

        // 데이터 배열
        pageItemList = new ArrayList<>();
        int purple_700 = Color.parseColor("#FF018786");
        int teal_200 = Color.parseColor("#03DAC5");
        int teal_700 = Color.parseColor("#018786");

        pageItemList.add(new PageItem(Color.RED, R.drawable.ic_pager_item_1, "안녕하세요 1 페이지 입니다!!"));
        pageItemList.add(new PageItem(Color.BLUE, R.drawable.ic_pager_item_2, "안녕하세요 2 페이지 입니다!!"));
        pageItemList.add(new PageItem(purple_700, R.drawable.ic_pager_item_3, "안녕하세요 3 페이지 입니다!!"));
        pageItemList.add(new PageItem(R.color.colorAccent, R.drawable.ic_pager_item_1, "안녕하세요 4 페이지 입니다!!"));
        pageItemList.add(new PageItem(R.color.black_ss, R.drawable.ic_pager_item_2, "안녕하세요 5 페이지 입니다!!"));
        pageItemList.add(new PageItem(R.color.colorWhite, R.drawable.ic_pager_item_3, "안녕하세요 6 페이지 입니다!!"));
        pageItemList.add(new PageItem(teal_200, R.drawable.ic_pager_item_1, "안녕하세요 7 페이지 입니다!!"));
        pageItemList.add(new PageItem(teal_700, R.drawable.ic_pager_item_2, "안녕하세요 8 페이지 입니다!!"));
        //pageItemList.add(new PageItem(R.color.teal_700, R.drawable.ic_pager_item_3, "안녕하세요 9 페이지 입니다!!"));
        pageItemList.add(new PageItem(R.color.colorOrange, R.drawable.ic_pager_item_3, "안녕하세요 9 페이지 입니다!!"));

        my_recycler_adapter = new MyIntroPagerRecyclerAdapter(this, pageItemList);
        mRecyclerView.setAdapter(my_recycler_adapter);

        // 가로로 페이지 이동
        mRecyclerView.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);

        dotsIndicator = (DotsIndicator) findViewById(R.id.dots_indicator);
        dotsIndicator.setViewPager2(mRecyclerView);
    }

    public void next_action(View view) {
        Toast.makeText(this, "click NEXT " , Toast.LENGTH_SHORT).show();
        mRecyclerView.setCurrentItem(mRecyclerView.getCurrentItem()+1);
    }

    public void pre_action(View view) {
        Toast.makeText(this, "click Pre " , Toast.LENGTH_SHORT).show();
        mRecyclerView.setCurrentItem(mRecyclerView.getCurrentItem()-1);
    }
}
MainActivity.java

MainActivity 실행되는 부분

 

    // ViewPager2
    implementation "androidx.viewpager2:viewpager2:1.0.0"
    // 애니메이션 효과
    implementation 'com.tbuonomo:dotsindicator:4.2'

build.gradle(Module)