Android ViewPager

안드로이드 / / 2021. 11. 14. 22:57
반응형

ViewPager 예제

  • 동적 추가 기능 구현
  • 동적 삭제 기능 구현
  • FragmentPageAdapter 사용

 

MainActivity.java

package com.srctree.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn_add;
    Button btn_delete;
    ViewPager viewpager;
    PagerAdapter mAdapter;
    int pageCount = 5;

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

        btn_add = findViewById(R.id.btn_add);
        btn_delete = findViewById(R.id.btn_delete);
        viewpager = findViewById(R.id.viewpager);

        btn_add.setOnClickListener(this);
        btn_delete.setOnClickListener(this);

        mAdapter = new PagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        viewpager.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View view) {
        if(view == btn_add) {//동적 페이지 추가
            pageCount++;
            mAdapter.notifyDataSetChanged();//동적 페이지 삭제
        } else if(view == btn_delete) {
            if(pageCount > 0) {
                pageCount--;
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    //ViewPager 어뎁터
    public class PagerAdapter extends FragmentPagerAdapter {
        public PagerAdapter(@NonNull FragmentManager fm, int behavior) {
            super(fm, behavior);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return PageFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            return pageCount;
        }

        //삭제시 정상적으로 적용되게 할려면 아래 필요!
        @Override
        public int getItemPosition(@NonNull Object object) {
            return FragmentPagerAdapter.POSITION_NONE;
        }
    }
}

PageFragment.java

package com.srctree.viewpager;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.Random;

public class PageFragment extends Fragment {
    int page;
    TextView tv_num;

    public static PageFragment newInstance(int page) {
        PageFragment fragment = new PageFragment();
        fragment.page = page;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        tv_num = view.findViewById(R.id.tv_num);
        tv_num.setText(page+"");
        
        //랜덤 배경색 적용
        Random random = new Random();
        int color = Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255));
        tv_num.setBackgroundColor(color);
        return view;
    }
}

activity_main.xml

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_add"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:text="Add"/>
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:text="Delete"/>
    </LinearLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>

fragment_page.xml

<?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">

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="50dp"
        android:text=""/>

</LinearLayout>

 

프로젝트 소스 다운↓

viewpager.zip
0.40MB

반응형

'안드로이드' 카테고리의 다른 글

Android Thread, Timer, CountDownTimer  (0) 2021.11.14
Android Fragment  (0) 2021.11.14
Android Webview(Remote, Local)  (2) 2021.11.14
Android Keyboard Show/Hide 이벤트 수신  (0) 2021.11.14
Android Permission(권한 요청)  (0) 2021.11.14
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기