1. 바로가기 메뉴 (NavigationDrawer)

화면의 좌상단에 위치한 모양의 아이콘을 눌렀을 때 나타나는 화면이며, NavigationDrawer라는 클래스로 제공된다.

이 메뉴는 여러 개의 화면에서 공통으로 적용되어 빠르게 메뉴 기능에 접근할 수 있다.


안드로이드 스튜디오에서 프로젝트 생성시, 

[File] - [New] - [New Project] - Empty Activity 가 아닌 Navigation Drawer Activity 를 선택한다.



2. 구현 결과 화면

      



3. AndroidManifest.xml

MainActivity에 NoActionBar 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="qlyh8.tistory.com.navigationdrawer">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
cs



4. values/styles.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<resources>
 
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 
    <!-- 액션바가 없어야 한다. -->
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
 
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
 
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
 
</resources>
 
cs



5. activity_main.xml


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
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
 
    <!-- 메인 화면 -->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <!-- 상단 바 -->
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
        </android.support.design.widget.AppBarLayout>
 
        <!-- 화면 -->
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
        </FrameLayout>
 
    </android.support.design.widget.CoordinatorLayout>
 
    <!-- 네비게이션 메뉴 화면-->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
 
</android.support.v4.widget.DrawerLayout>
 
cs



6. nav_header_main.xml


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
<?xml version="1.0" encoding="utf-8"?>
<!-- 네비게이션 메뉴 상단 화면 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@mipmap/ic_launcher_round" />
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="qlyh8"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="qlyh8.tistory.com" />
 
</LinearLayout>
 
cs



7. activity_main_drawer.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<!-- 네비게이션 메뉴 하단 화면 -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
 
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav1"
            android:icon="@drawable/ic_menu_camera"
            android:title="첫 번째 화면" />
        <item
            android:id="@+id/nav2"
            android:icon="@drawable/ic_menu_gallery"
            android:title="두 번째 화면" />
        <item
            android:id="@+id/nav3"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="세 번째 화면" />
    </group>
 
</menu>
 
cs



8. fragment1.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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:background="@android:color/holo_blue_light"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫 번째 화면"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textColor="@android:color/white"/>
</LinearLayout>
cs

fragment2.xml, fragment3.xml 코드 동일



9. Fragment1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package qlyh8.tistory.com.navigationdrawer;
 
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
public class Fragment1 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) getLayoutInflater().inflate(R.layout.fragment1, container, false);
        return rootView;
    }
}
 
cs

Fragment2.java, Fragment3.java 코드 동일



10. MainActivity.java

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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package qlyh8.tistory.com.navigationdrawer;
 
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
 
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback {
 
    Toolbar toolbar;
    Fragment fragment1, fragment2, fragment3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // 상단 바 설정
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        // 전체 화면 설정
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
 
        // 네비게이션 화면 설정
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this); // 리스너 설정
 
        // 프래그먼트 화면 설정
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment1).commit();
    }
 
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    // 네비게이션 메뉴 클릭 이벤트
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
 
        if (id == R.id.nav1) {
            onChangedFragment(1null);
        } else if (id == R.id.nav2) {
            onChangedFragment(2null);
        } else if (id == R.id.nav3) {
            onChangedFragment(3null);
        }
 
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
 
    // 프래그먼트 화면 전환 이벤트
    @Override
    public void onChangedFragment(int position, Bundle bundle) {
        Fragment fragment = null;
 
        switch (position){
            case 1:
                fragment = fragment1;
                toolbar.setTitle("첫 번째 화면");
                break;
            case 2:
                fragment = fragment2;
                toolbar.setTitle("두 번째 화면");
                break;
            case 3:
                fragment = fragment3;
                toolbar.setTitle("세 번째 화면");
                break;
             default:
                 break;
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
    }
}
 
cs



11. FragmentCallback.java

1
2
3
4
5
6
7
8
9
package qlyh8.tistory.com.navigationdrawer;
 
import android.os.Bundle;
 
// 프래그먼트 전환 인터페이스
public interface FragmentCallback {
    void onChangedFragment(int position, Bundle bundle);
}
 
cs



12. 참고 사이트

Create a Navigation Drawer: https://developer.android.com/training/implementing-navigation/nav-drawer.html





출처: https://www.edwith.org/boostcourse-android/lecture/20684/

'Android' 카테고리의 다른 글

ANR (Application Not Responding)  (0) 2018.07.17
프래그먼트(Fragment) 특징  (0) 2018.07.17
뷰페이저 (ViewPager)  (0) 2018.07.10
탭 (Tab)  (0) 2018.07.05
액션바 (ActionBar) & 옵션메뉴 (OptionMenu)  (0) 2018.07.05

1. 뷰페이저 (ViewPager)

뷰페이저는 좌우 스크롤을 통해 여러 개의 화면을 전환할 수 있도록 만든 것이다.

뷰페이저 안에 들어가는 각각의 화면은 프래그먼트로 만들 수 있고, 어댑터를 사용하여 프래그먼트들을 관리할 수 있다.

프래그먼트를 하나의 아이템으로 관리하는 어댑터는 SDK에서 제공되는 어댑터인 FragmentStatePagerAdapter 클래스를 사용한다.



2. 구현 결과 화면

    



3. activity_main.xml

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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="두 번째 화면 보기"
        android:textSize="18sp" />
 
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
 
        <!-- 현재 보고 있는 프래그먼트가 몇 번째 프래그먼트인지 알 수 있게 해준다. -->
        <android.support.v4.view.PagerTitleStrip
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/black"
            android:textColor="#FFFFFF"
            android:paddingTop="5dp"
            android:paddingBottom="5dp">
        </android.support.v4.view.PagerTitleStrip>
 
        <!--<android.support.v4.view.PagerTabStrip
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/black"
            android:textColor="#FFFFFF"
            android:paddingTop="5dp"
            android:paddingBottom="5dp">
        </android.support.v4.view.PagerTabStrip>-->
 
    </android.support.v4.view.ViewPager>
 
</RelativeLayout>
 
cs


4. viewpager_fragment1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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:background="@android:color/holo_blue_light"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫 번째 화면"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textColor="@android:color/white"/>
</LinearLayout>
 
cs


viewpager_fragment2.xml, viewpager_fragment3.xml 동일



5. ViewPagerFragment1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.tistory.qlyh8.pracitice;
 
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
public class ViewPagerFragment1 extends Fragment{
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) getLayoutInflater().inflate(R.layout.viewpager_fragment1, container, false);
        return rootView;
    }
}
 
cs


ViewPagerFragment2.java, ViewPagerFragment3.java 동일



6. MainActivity.java
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
package com.tistory.qlyh8.pracitice;
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity  {
 
    Button button;
    ViewPager viewPager;
    ViewPagerFragment1 viewPagerFragment1;
    ViewPagerFragment2 viewPagerFragment2;
    ViewPagerFragment3 viewPagerFragment3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        viewPager = findViewById(R.id.view_pager);
        // 화면에 보이지 않는 프래그먼트는 캐싱을 해서 미리 프래그먼트를 뒤에 담아 놓고, 스크롤 시에 보여준다.
        // 이 메서드는 캐싱을 해놓을 프래그먼트 개수를 지정한다.
        viewPager.setOffscreenPageLimit(3);
 
        // 어댑터 설정
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerFragment1 = new ViewPagerFragment1();
        adapter.addItem(viewPagerFragment1);
        viewPagerFragment2 = new ViewPagerFragment2();
        adapter.addItem(viewPagerFragment2);
        viewPagerFragment3 = new ViewPagerFragment3();
        adapter.addItem(viewPagerFragment3);
        viewPager.setAdapter(adapter);
 
        // 버튼 설정, 두 번째 화면을 보여준다.
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(1);
            }
        });
    }
 
    // 각 아이템을 프래그먼트를 넣는 경우에, FragmentStatePagerAdapter 클래스를 상속하여 만든다.
    class ViewPagerAdapter extends FragmentStatePagerAdapter {
 
        ArrayList<Fragment> arrayList = new ArrayList<>();
 
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }
 
        // 프래그먼트 추가
        public void addItem(Fragment item){
            arrayList.add(item);
        }
 
        @Override
        public Fragment getItem(int position) {
            return arrayList.get(position);
        }
 
        @Override
        public int getCount() {
            return arrayList.size();
        }
 
        // 제목 텍스트 나타내기
        @Override
        public CharSequence getPageTitle(int position) {
            int num = position+1;
            return "페이지 " + num;
        }
    }
}
cs


7. 참고
Slide Between Fragments with ViewPager 






1. 실행 결과 화면

    



2. values/styles.xml

parent 정보를 NoActionBar로 변경하여 기존 액션바를 지운다.

1
2
3
4
5
6
7
8
9
10
11
12
<resources>
 
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 
</resources>
 
cs



3. build.gradle (app)

dependency에 com.android.support:design 추가

1
compile 'com.android.support:design:26.1.0'
cs



4. acitivity_main.xml

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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <!-- 상단의 액션바 부분과 가운데 내용이 보이는 부분이 함께 들어가면 겹쳐서 보이는 현상이 생긴다.
    CoordinatorLayout 을 사용하면 이를 해결하고 두 부분의 크기가 잘 맞게 보이게 한다. -->
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <!-- 액션바 영역 -->
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
 
            <!-- 액션바 타이틀 및 메뉴 아이콘 영역 -->
            <!-- elevation: 앞으로 튀어나와 보이는 효과 -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimaryDark"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                android:elevation="1dp">
            </android.support.v7.widget.Toolbar>
 
            <!-- 탭 영역 -->
            <!-- tabMode: 탭을 고정
                 tabGravity: 탭 버튼을 꽉 채워서 추가 -->
            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:elevation="1dp"
                android:background="@android:color/background_light"
                app:tabMode="fixed"
                app:tabGravity="fill"
                app:tabTextColor="@color/colorPrimary"
                app:tabSelectedTextColor="@color/colorAccent">
            </android.support.design.widget.TabLayout>
 
        </android.support.design.widget.AppBarLayout>
 
        <!-- 화면 영역-->
        <!-- layout_behavior: 액션바와 프레임 레이아웃 간의 위치를 잡아 준다. -->
        <FrameLayout
            android:id="@+id/frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
 
    </android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
 
cs



5. tab_fragment1.xml

tab_fragment2.xml, tab_fragment3.xml 동일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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:background="@android:color/holo_blue_light"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫 번째 화면"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textColor="@android:color/white"/>
</LinearLayout>
 
cs



6. TabFragment1.java

TabFragment2.java, TabFragment3.java 동일

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.tistory.qlyh8.pracitice;
 
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
public class TabFragment1 extends Fragment{
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) getLayoutInflater().inflate(R.layout.tab_fragment1, container, false);
        return rootView;
    }
}
 
cs



7. MainActivity.java

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
package com.tistory.qlyh8.pracitice;
 
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
 
public class MainActivity extends AppCompatActivity  {
 
    TabFragment1 tabFragment1;
    TabFragment2 tabFragment2;
    TabFragment3 tabFragment3;
    Toolbar toolbar;
    TabLayout tabLayout;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // 액션바 설정
        toolbar =  findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        tabFragment1 = new TabFragment1();
        tabFragment2 = new TabFragment2();
        tabFragment3 = new TabFragment3();
 
        // 기본 화면으로 TabFragment1 화면 설정
        getSupportFragmentManager().beginTransaction().add(R.id.frame_layout, tabFragment1).commit();
 
        // 탭 설정
        tabLayout = findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("탭 1"));
        tabLayout.addTab(tabLayout.newTab().setText("탭 2"));
        tabLayout.addTab(tabLayout.newTab().setText("탭 3"));
 
        // 탭 별 화면 설정
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Fragment selectedFragment = null;
 
                switch (tab.getPosition()) {
                    case 0:
                        selectedFragment = tabFragment1;
                        break;
                    case 1:
                        selectedFragment = tabFragment2;
                        break;
                    case 2:
                        selectedFragment = tabFragment3;
                        break;
                    default:
                        break;
                }
 
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, selectedFragment).commit();
            }
 
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
 
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }
}
cs



8. 참고

ActionBar Tabs with Fragments: https://github.com/codepath/android_guides/wiki/ActionBar-Tabs-with-Fragments





출처: https://www.edwith.org/boostcourse-android/lecture/17077/


+ Recent posts