[서울시 앱 공모전 / 서울시를 이겨라] ViewPager with fragments

2017. 11. 24. 02:15Android

# BlankFragment 생성





# BlankFragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
public class BlankFragment extends Fragment {
 
    View view;
 
    public BlankFragment(){
 
    }
 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        view = inflater.inflate(R.layout.fragment_blank, container, false);
        
        return view;
    }
}
 
cs



# fragment_blank.xml 기본 형태임


# MainActivity.java


BottomNavigationView 해당 메뉴를 누르면 BlankFragment로 생성한 fragment 객체들이 변경되는 것을 확인할 수 있음

Fragment replace를 해줌


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.view.MenuItem;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    BottomNavigationView bottomNavigationView;
 
    Fragment fragment;
    BlankFragment homeFragment;
    BlankFragment facilityFragment;
    BlankFragment arFragment;
    BlankFragment pathInfoFragment;
    BlankFragment settingsFragment;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.activity_main);
 
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
 
        homeFragment = new BlankFragment();
        facilityFragment = new BlankFragment();
        arFragment = new BlankFragment();
        pathInfoFragment = new BlankFragment();
        settingsFragment = new BlankFragment();
 
        fragment = homeFragment;
        switchFragment();
 
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_home:
                        fragment = homeFragment;
                        switchFragment();
                        break;
                    case R.id.action_facility:
                        fragment = facilityFragment;
                        switchFragment();
                        break;
                    case R.id.action_AR:
                        fragment = arFragment;
                        switchFragment();
                        break;
                    case R.id.action_route:
                        fragment = pathInfoFragment;
                        switchFragment();
                        break;
                    case R.id.action_settings:
                        fragment = settingsFragment;
                        switchFragment();
                        break;
                }
                return true;
            }
        });
    }
 
    public void switchFragment() {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.main_fragment_place, fragment);
        fragmentTransaction.commit();
 
        if(fragment == homeFragment){
            Toast.makeText(getApplicationContext(), "home fragment", Toast.LENGTH_SHORT).show();
        }
        else if(fragment == facilityFragment){
            Toast.makeText(getApplicationContext(), "facility fragment", Toast.LENGTH_SHORT).show();
        }
        else if(fragment == arFragment){
            Toast.makeText(getApplicationContext(), "AR fragment", Toast.LENGTH_SHORT).show();
        }
        else if(fragment == pathInfoFragment){
            Toast.makeText(getApplicationContext(), "path information fragment", Toast.LENGTH_SHORT).show();
        }
        else if(fragment == settingsFragment){
            Toast.makeText(getApplicationContext(), "settings fragment", Toast.LENGTH_SHORT).show();
        }
    }
}
cs



# Fragment에 대한 기본 정리

https://medium.com/@henen/%EB%B9%A0%EB%A5%B4%EA%B2%8C%EB%B0%B0%EC%9A%B0%EB%8A%94-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-fragment-2-activity-fragment%EB%A1%9C-%EC%89%BD%EA%B2%8C-%EB%B3%80%EA%B2%BD-d0e0e3efd7


https://medium.com/@henen/%EB%B9%A0%EB%A5%B4%EA%B2%8C%EB%B0%B0%EC%9A%B0%EB%8A%94-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-fragment-4-fragment%EA%B0%84-%EC%97%90-%EB%8D%B0%EC%9D%B4%ED%84%B0%EC%A0%84%EB%8B%AC-c6ab1d0766af


Fragment 재실행 에러 및 안드로이드 API Level에 따른 에러 이슈 정리

BottomNavigationView Menu item 선택된 것을 누르면 따로 fragment를 생성하지 않고 현재 fragment를 유지하게 만들었음


https://www.tutorialspoint.com/android/android_fragment_transitions.htm


http://itpangpang.tistory.com/267




# Fragment 샘플 영상




# ViewPager 추가


처음에 ViewPager 내부에 fragment를 미리 생성해서 집어넣어버리기 때문에 미리 만들어놓고 불러오면 빠르게 메인화면을 로딩 할 수 있다.

BottomNavigationView 메뉴 클릭 시, Fragment를 변경시켜주는데 옆으로 움직이는 효과를 줄 수 있고

Fragment를 슬라이드를 했을 시에 fragment를 변경시켜줄 수 있어서 사용자에게 UX적으로 편리함을 제공할 수 있다.


ViewPagerAdapter 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import android.app.Fragment;
import android.app.FragmentManager;
 
import java.util.ArrayList;
import java.util.List;
 
public class ViewPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
 
    public List<Fragment> mFragmentList = new ArrayList<>();
 
    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }
 
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
 
    @Override
    public int getCount() {
        return mFragmentList.size();
    }
 
    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }
 
    public void switchFragment(int position, Fragment fragment){
        mFragmentList.remove(position);
        mFragmentList.add(position, fragment);
    }
}
cs



activity_main.xml 파일에 ViewPager를 아래와 같이 추가를 해주면 된다.

<android.support.v4.view.ViewPager
android:id="@+id/mainViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/activity_main"/>

권한을 설정을 해줘야 v13.FragmentStatePagerAdapter을 사용할 수 있다

public class ViewPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter


compile 'com.android.support:support-v13:25.0.0'

gradle에 추가해주면 된다.


혹시 gradle에 추가했는데 빨간 줄이 생기면 라이브러리가 없어서 그런거일 수도 있으니까 아래와 같이 라이브러리 다운로드 하면 된다.


# 라이브러리 다운로드 방법






# ViewPager 샘플 영상






#예제 코드는 Github에서 볼 수 있습니다


# 참고 사이트

Fragment


ViewPager

http://itpangpang.xyz/284

https://www.youtube.com/watch?v=W_WCPDto3QM