본문 바로가기
(Android App)안드로이드 앱

(Android App)안드로이드 스튜디오: 뷰페이저2, Viewpager2 기초

by 공부가싫다가도좋아 2021. 2. 23.
반응형

Viewpager2


*참고

더보기

책으로 공부하다가 책에서 Viewpager을 가르쳐주는데

안드로이드 스튜디오에서 눈을 씻고 찾아봐도 Viewpager2는 있어도 Viewpager은 없더라구요.

그래서 찾아보니 기존 Viewpager은 없어지고

(직접 xml에서 쓰면 쓸 수 있긴 합니다, 근데 굳이 구 버전을 쓸 필요가 없겠죠!!)

업그레이드 된 Viewpager2 가 나왔다고 합니다.

 

Mainactivity.java

package org.techtown.navigation;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.accessibilityservice.AccessibilityService;
import android.os.Bundle;
import android.view.View;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final int NUM_PAGES=3;  //페이지 수
    private ViewPager2 pager;
    private FragmentStateAdapter pagerAdapter;

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

        pager=findViewById(R.id.pager);
        pagerAdapter=new ScreeSlidePagerAdapter(this);
        pager.setAdapter(pagerAdapter);

    }


//뒤로가기 눌렀을때 처리
//뷰페이저2 동작하는 것과 상관 없으므로 (onBackPressed 메소드)생략 가능
    @Override  
    public void onBackPressed() {  
        if(pager.getCurrentItem()==0){
        	Toast.makeText(this, "뒤로가기가 눌렸습니다.", Toast.LENGTH_SHORT).show();
            super.onBackPressed();
        }else{
            pager.setCurrentItem(pager.getCurrentItem()-1);
        }
    }
    
//페이저와 프래그먼트 이어주기
    private class ScreeSlidePagerAdapter extends FragmentStateAdapter{  
        public ScreeSlidePagerAdapter(FragmentActivity fa){
            super (fa);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {//포지션마다 있을 fragment설정
            if(position==0) return new Ex01Fragment();  
            else if(position==1) return new Ex02Fragment();
            else return new Ex03Fragment();
        }

        @Override
        public int getItemCount() {
            return NUM_PAGES;  //페이지 수 지정.
        }
    }



}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
	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"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

*참고

더보기

Ex01Fragment,Ex02Fragment,Ex03Fragment 는 다 똑같습니다. 그냥 복붙 해도 되지만

R.layout.fragment_ex01 <-이부분에서 연결할 fragment와 알맞게 바꿔주시기 바랍니다. 잘모르겠으면 아래 똑같이 따라하시면 됩니다.

Ex01Fragment.java

package org.techtown.navigation;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Ex01Fragment extends Fragment {


    public Ex01Fragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ex01, container, false);
    }
}

 

fragment_ex01.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E39999"
    android:orientation="vertical"
    tools:context=".Ex01Fragment" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="첫 번째 페이지"
        android:textSize="30sp" />
</LinearLayout>

 

Ex02Fragment

package org.techtown.navigation;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

public class Ex02Fragment extends Fragment {


    public Ex02Fragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ex02, container, false);
    }
}

 

fragment_ex02.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BFACE1"
    android:orientation="vertical"
    tools:context=".Ex01Fragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="두 번째 페이지"
        android:textSize="30sp" />
</LinearLayout>

 

Ex03Fragment.java

package org.techtown.navigation;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

public class Ex03Fragment extends Fragment {


    public Ex03Fragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ex03, container, false);
    }
}

 

fragment_ex03.xlm

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ECD38A"
    android:orientation="vertical"
    tools:context=".Ex01Fragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="세 번째 페이지"
        android:textSize="30sp" />
</LinearLayout>

 

#결과물

반응형

댓글