MainActivity

...더보기
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package com.example.boostcoursepractice;
 
import android.os.Bundle;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
 
import android.view.View;
 
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
 
import android.view.MenuItem;
 
import com.google.android.material.navigation.NavigationView;
 
import androidx.drawerlayout.widget.DrawerLayout;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
 
import android.view.Menu;
import android.widget.FrameLayout;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback {
 
    Fragment fragment1 ;
    Fragment fragment2;
    Fragment fragment3 ;
    Toolbar toolbar ;
 
    @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);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
 
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3() ;
 
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment1).commit();
    }
 
    @Override
    public void onFragmentSelected(int position, Bundle bundle) {
        Fragment curFragment = null ;
 
        if(position == 0)
        {
            curFragment = fragment1 ;
            toolbar.setTitle("첫번째 화면");
        }
 
        else if(position == 1)
        {
            curFragment = fragment2 ;
            toolbar.setTitle("두번째 화면");
        }
 
        else if(position == 2)
        {
            curFragment = fragment3 ;
            toolbar.setTitle("세번째 화면");
        }
 
        getSupportFragmentManager().beginTransaction().replace(R.id.container, curFragment).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) {
        // Inflate the menu; this adds items to the action bar if it is present.
        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) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
 
        if (id == R.id.nav_0) {
            Toast.makeText(this"첫번째 화면 선택됨", Toast.LENGTH_SHORT).show();
            onFragmentSelected(0null);
        } else if (id == R.id.nav_1) {
            Toast.makeText(this"두번째 화면 선택됨", Toast.LENGTH_SHORT).show();
            onFragmentSelected(1null);
        } else if (id == R.id.nav_2) {
            Toast.makeText(this"세번째 화면 선택됨", Toast.LENGTH_SHORT).show();
            onFragmentSelected(2null);
        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
 
 
 
 
cs

 

FragmentCallBack

...더보기
1
2
3
4
5
6
7
8
9
10
package com.example.boostcoursepractice;
 
import android.os.Bundle;
 
public interface FragmentCallback {
 
    public void onFragmentSelected(int position, Bundle bundle) ;
 
}
 
cs

 

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
52
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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">
 
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:context=".MainActivity">
 
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
 
            <androidx.appcompat.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" />
 
        </com.google.android.material.appbar.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>
 
 
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
 
    <com.google.android.material.navigation.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" />
 
</androidx.drawerlayout.widget.DrawerLayout>
 
cs

 

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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@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:contentDescription="@string/nav_header_desc"
        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="@string/nav_header_title"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/nav_header_subtitle" />
 
</LinearLayout>
 
cs

 

menu/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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?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/nav_0"
            android:icon="@drawable/ic_menu_camera"
            android:title="첫번째 화면" />
        <item
            android:id="@+id/nav_1"
            android:icon="@drawable/ic_menu_gallery"
            android:title="두번째 화면" />
        <item
            android:id="@+id/nav_2"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="세번째 화면" />
        <item
            android:id="@+id/nav_3"
            android:icon="@drawable/ic_menu_manage"
            android:title="네번째 화면" />
    </group>
 
    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="@string/menu_share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="@string/menu_send" />
        </menu>
    </item>
 
</menu>
 
cs

 

Fragment1

Fragment2

Fragemet3

fragment1.xml

fragment2.xml

fragment3.xml

 

이런 것들은 전글에 있던 것과 아예  같다.

 

 

 

 

우선 바로가기 메뉴를 만들기 위해서는 프로젝트를 생성할 때 Navigation Drawer Activity로 애초에 만드는 것이 편하다. 그러면 여러가지가 생길 텐데 위 예제처럼 app_bar_main.xml, content_main.xml을 activity_main.xml에 합쳐서 한개의 파일로 만드는 것이 편하다. 이제는 저렇게 만들어져 있는 것을 구조를 파악하고 수정하는 것이 중요하다. 위 예제에서는 바로가기 메뉴에 첫번째 두번째 세번째 화면을 클릭하면 해당 프래그먼트를 띄우도록하는 것이다. 

 

 public boolean onNavigationItemSelected(MenuItem item) {

        // Handle navigation view item clicks here.

        int id = item.getItemId();

 

        if (id == R.id.nav_0) {

            Toast.makeText(this"첫번째 화면 선택됨", Toast.LENGTH_SHORT).show();

            onFragmentSelected(0null);

        } else if (id == R.id.nav_1) {

            Toast.makeText(this"두번째 화면 선택됨", Toast.LENGTH_SHORT).show();

            onFragmentSelected(1null);

        } else if (id == R.id.nav_2) {

            Toast.makeText(this"세번째 화면 선택됨", Toast.LENGTH_SHORT).show();

            onFragmentSelected(2null);

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        drawer.closeDrawer(GravityCompat.START);

        return true;

    }

 

위 처럼 onNavigationItemSelected(MenuItem item)메서드를 오버라이드 해주면 바로가기 메뉴의 어떤 메뉴버튼이 눌렸는지 콜백함수가 작동한다. 버튼이 눌릴 때마다 프래그먼트를 바꿔줘야 하는데 이 때 액티비티의 프래그먼트 매니저를 이용해야 함으로 

 

package com.example.boostcoursepractice;

 

import android.os.Bundle;

 

public interface FragmentCallback {

 

    public void onFragmentSelected(int position, Bundle bundle) ;

 

}

 

위와 같은 FragmentCallback이라는 인터페이스를 만들고 이를 메인 액티비티에서 인터페이스를 implement해준다. 그리고 인터페이스에서 선언된 함수를 

 

@Override

    public void onFragmentSelected(int position, Bundle bundle) {

        Fragment curFragment = null ;

 

        if(position == 0)

        {

            curFragment = fragment1 ;

            toolbar.setTitle("첫번째 화면");

        }

 

        else if(position == 1)

        {

            curFragment = fragment2 ;

            toolbar.setTitle("두번째 화면");

        }

 

        else if(position == 2)

        {

            curFragment = fragment3 ;

            toolbar.setTitle("세번째 화면");

        }

 

        getSupportFragmentManager().beginTransaction().replace(R.id.container, curFragment).commit();

    }

 

위와 같이 오버라이드 해주고 프래그먼트를 바꿔줄 때마다 위 함수를 호출하면 된다.

 

 

 

 

 

 

 

결과화면1

 

결과화면2

 

+ Recent posts