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

 

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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.Toolbar;
 
import com.google.android.material.tabs.TabLayout;
 
import java.util.ArrayList;
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
ViewPager pager ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        pager = (ViewPager) findViewById(R.id.pager) ;
        pager.setOffscreenPageLimit(3);
 
        MoviePagerAdapter moviePagerAdapter = new MoviePagerAdapter(getSupportFragmentManager());
 
        Fragment fragment1 = new Fragment1();
        moviePagerAdapter.addItem(fragment1);
 
        Fragment fragment2 = new Fragment2();
        moviePagerAdapter.addItem(fragment2);
 
        Fragment fragment3 = new Fragment3();
        moviePagerAdapter.addItem(fragment3);
 
        pager.setAdapter(moviePagerAdapter);
 
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(1);
}
});
    }
 
    class MoviePagerAdapter extends FragmentStatePagerAdapter
    {
        ArrayList<Fragment> items = new ArrayList<Fragment>();
 
        public MoviePagerAdapter(FragmentManager fm) {
            super(fm);
 
        }
 
        public void addItem(Fragment item)
        {
            items.add(item);
        }
 
        @Override
        public Fragment getItem(int position) {
            return items.get(position);
        }
 
        @Override
        public int getCount() {
            return items.size();
        }
 
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return "페이지" + position;
}
    }
}
 
 
 
 
cs
 
 
 

 

Fragment1

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
 
public class Fragment1 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment1, container, false);
 
        return rootView;
    }
}
 
cs

 

Fragment2

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
 
public class Fragment2 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment2, container, false);
 
        return rootView;
    }
}
 
cs

 

Fragment3

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
 
public class Fragment3 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment3, container, false);
 
        return rootView;
    }
}
 
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
<?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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:text="두 번째 보기" />
 
    <androidx.viewpager.widget.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button"
        android:layout_alignParentLeft="true"
        android:id="@+id/pager">
 
<androidx.viewpager.widget.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#55cedf"
android:paddingTop="5dp"
android:paddingBottom="5dp"
></androidx.viewpager.widget.PagerTitleStrip>
 
    </androidx.viewpager.widget.ViewPager>
</RelativeLayout>
 
 
 
cs

 

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:background="@color/design_default_color_primary"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫번째"
        android:textSize="40dp" />
 
</LinearLayout>
cs

 

fragment2.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:background="@color/colorAccent"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="두번째"
        android:textSize="40dp" />
 
</LinearLayout>
cs

 

fragment3.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:background="@android:color/holo_green_dark"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="세번째"
        android:textSize="40dp" />
 
</LinearLayout>
cs

 

우선 뷰페이저를 만들기 위해서 메인액티비티 xml파일에 뷰페이저 태그를 만들어 추가해주었다.

이제 메인액티비의 자바코드로 가보자. 방금 만든 뷰페이저를 찾아 참조해주어 pager를 만들고 그 페이저에 어댑터를 만들어 줘야 한다.

 

class MoviePagerAdapter extends FragmentStatePagerAdapter

    {

        ArrayList<Fragment> items = new ArrayList<Fragment>();

 

        public MoviePagerAdapter(FragmentManager fm) {

            super(fm);

 

        }

 

        public void addItem(Fragment item)

        {

            items.add(item);

        }

 

        @Override

        public Fragment getItem(int position) {

            return items.get(position);

        }

 

        @Override

        public int getCount() {

            return items.size();

        }

    }

 

위 처럼 FragmentStatePagerAdapter만들어 어댑터를 만들어 줘야 하고 필수로생성자를 만들고 getItem, getCount를 오버라이드 해줘야 된다. 추가로 addItem을 만들어 어댑터의 아이템을 추가할 수 있도록 한다.

 

 MoviePagerAdapter moviePagerAdapter = new MoviePagerAdapter(getSupportFragmentManager());

 

        Fragment fragment1 = new Fragment1();

        moviePagerAdapter.addItem(fragment1);

 

        Fragment fragment2 = new Fragment2();

        moviePagerAdapter.addItem(fragment2);

 

        Fragment fragment3 = new Fragment3();

        moviePagerAdapter.addItem(fragment3);

 

        pager.setAdapter(moviePagerAdapter);

 

 

마지막으로 어댑터를 만들어주고 생성자의 매개변수로 액티비티의 프래그먼트 매니저를 전달해 주고 어댑터의 아이템을 추가해주고 마지막으로 페이저에 어댑터를 설정해주면 끝난다.

 

 

 

 

 

페이지 스트립을 만드는 것은 매우 간다하다. 그냥 아까 만든 뷰페이저 안에 

 

<androidx.viewpager.widget.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#55cedf"
android:paddingTop="5dp"
android:paddingBottom="5dp"
></androidx.viewpager.widget.PagerTitleStrip>

 

라고 태그만 추가해주고 페이저 어댑터의 

 

@Nullable
@Override
public CharSequence getPageTitle(int position) {
return "페이지" + position;
}

 

이 함수만 추가적으로 오버라이드 해주면 된다.

 

 

 

 

 

결과 화면

 

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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.Toolbar;
 
import com.google.android.material.tabs.TabLayout;
 
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
    Fragment1 fragment1;
    Fragment2 fragment2;
    Fragment3 fragment3;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        androidx.appcompat.widget.Toolbar toolbar = (androidx.appcompat.widget.Toolbar ) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3() ;
 
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment1).commit();
 
        TabLayout tabs= (TabLayout)findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setText("친구"));
        tabs.addTab(tabs.newTab().setText("일대일 채팅"));
        tabs.addTab(tabs.newTab().setText("기타"));
 
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
 
                Fragment selectedFragment = null ;
                if(position == 0 ) {
                    selectedFragment = fragment1;
                } else  if(position == 1 ) {
                    selectedFragment = fragment2;
                } else  if(position == 2 ) {
                    selectedFragment = fragment3;
                }
 
                getSupportFragmentManager().beginTransaction().replace(R.id.container, selectedFragment).commit();
 
            }
 
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
 
            }
 
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
 
            }
        });
    }
}
 
 
 
 
cs

 

Fragment1

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class Fragment1 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
 
        return rootView;
    }
}
 
cs

 

Fragment2

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class Fragment2 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment2, container, false);
 
        return rootView;
    }
}
 
cs

 

Fragment3

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class Fragment3 extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment3, container, false);
 
        return rootView;
    }
}
 
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
<?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">
 
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent">
 
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
 
            <androidx.appcompat.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimaryDark"
                android:theme="@style/ThemeOverlay.AppCompat.Dark"
                android:elevation="1dp"
                android:id="@+id/toolbar"></androidx.appcompat.widget.Toolbar>
 
 
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/background_light"
                android:elevation="1dp"
                app:tabMode="fixed"
                app:tabGravity="fill"
                app:tabTextColor="@color/colorPrimary"
                app:tabSelectedTextColor="@color/colorAccent"
                ></com.google.android.material.tabs.TabLayout>
 
        </com.google.android.material.appbar.AppBarLayout>
        
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/container"></FrameLayout>
 
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
 
</RelativeLayout>
cs

 

fragment1.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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:background="@android:color/holo_blue_bright"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="첫 번째 화면"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="다음" />
</LinearLayout>
cs

 

fragment2.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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:background="@color/design_default_color_primary"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="두 번째 화면"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="다음" />
</LinearLayout>
cs

 

fragment3.xml

 

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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:background="@android:color/holo_green_dark"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="세 번째 화면"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="다음" />
</LinearLayout>
cs

values/styles.xml

...더보기

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

 

build.gradle

...더보기

apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.example.boostcoursepractice"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.android.support:design:29.+'
}

 

우선 사용자 정의 액션바를 달고 밑에 탭까지 달기 위해서는 위 처럼 style에서 

 

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

 

을 설정해줘야 하고 또 gradle에서

 

implementation 'com.android.support:design:29.+'

 

포함시켜야만 한다. 이렇게 하고 나서 acitivity_main을 보자 우선 전체를 CoordinatorLayout로 감싸야 하고 그안에

AppBarLayout가 들어야가하고 또 그안에 Toolbar(액션바) TabLayout(탭) 을 설정해주면 된다. 다 설정해준 후 다시 CoordinatorLayout안에 액션바와 탭을 제외한 진짜 레이아웃을 정의해주면 된다. 여기서는 

 

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:id="@+id/container"></FrameLayout>

 

이렇게 해주었고 이때 

 

app:layout_behavior="@string/appbar_scrolling_view_behavior"

 

이 속성을 꼭 빼먹지 않아야 잘 작동한다.

 

다시 메인 액티비티로 돌아와 

 

androidx.appcompat.widget.Toolbar toolbar = (androidx.appcompat.widget.Toolbar ) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

 

이렇게 툴바를 찾아주고 그것을 다시 액션바 설정 까지 해줘야 한다. 탭바는

 

TabLayout tabs= (TabLayout)findViewById(R.id.tabs);
tabs.addTab(tabs.newTab().setText("친구"));
tabs.addTab(tabs.newTab().setText("일대일 채팅"));
tabs.addTab(tabs.newTab().setText("기타"));

 

이렇게 찾아주고 addTab 과 newTab 으로 항목을 추가해 주면 된다. 탭 바에 클릭 되었을 때는 

 

tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {

int position = tab.getPosition();

Fragment selectedFragment = null ;
if(position == 0 ) {
selectedFragment = fragment1;
} else if(position == 1 ) {
selectedFragment = fragment2;
} else if(position == 2 ) {
selectedFragment = fragment3;
}

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

}

 

이런식으로 리스너를 등록하여 선택된 탭의 position을 가지고 구별하여 기능의 구현한다.

 

 

 

 

결과화면

 

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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
 
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
       /* ActionBar abar = getSupportActionBar();
        abar.hide();*/
 
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
 
        getMenuInflater().inflate(R.menu.menu_main, menu);
 
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int curId = item.getItemId();
 
        switch (curId) {
            case R.id.menu_12:
                Toast.makeText(this"12클릭됨", Toast.LENGTH_SHORT).show();
                break;
 
            case R.id.menu_15:
                Toast.makeText(this"15클릭됨", Toast.LENGTH_SHORT).show();
                break;
 
            case R.id.menu_19:
                Toast.makeText(this"19클릭됨", Toast.LENGTH_SHORT).show();
                break;
 
            default:
                break;
        }
 
        return super.onOptionsItemSelected(item);
    }
}
 
 
cs

 

layout/search_layout.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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="wrap_content"
    android:orientation="horizontal">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="검색"
        android:textColor="#ffad8745"
        android:textSize="16dp"></TextView>
 
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="4dp"></EditText>
 
</LinearLayout>
cs

 

menu/menu_main.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <item android:title="12세"
        android:id="@+id/menu_12"
        android:icon="@drawable/ic_12"
        app:showAsAction="always"/>
 
    <item android:title="15세"
        android:id="@+id/menu_15"
        android:icon="@drawable/ic_15"
        app:showAsAction="always|withText"
        app:actionLayout="@layout/search_layout"/>
 
    <item android:title="19세"
        android:id="@+id/menu_19"
        android:icon="@drawable/ic_19"
        app:showAsAction="always"/>
 
</menu>
cs

 

일단 맨처음에 액션바에 메뉴를 만들려면 res폴더에 menu라는 폴더를 만들어 주고 그 안에 xml파일을 만들어 준다.(여기서는 menu_main.xml 을 만들어 줌) 이 xml 파일에는 item이라는 테그로 메뉴화면 보일 아이템들을 설정해주었다.

다 설정하고 나면 메인 액티비티로 돌아가 

 

@Override

    public boolean onCreateOptionsMenu(Menu menu) {

 

        getMenuInflater().inflate(R.menu.menu_main, menu);

 

        return true;

    }

 

이렇게 onCreateOptionsMenu(Menu menu) 콜백 함수에서 메뉴 xml파일을 인플레이트 해주는 함수로 오버라이드 해주면 액션바에 메뉴가 생기게 되어 진다. 또한 아이템이 클릭 되었을 때는

 

 public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        

위의 콜백함수를 오버라이드 하여 아이템의 아이디 값을 얻어 그것 구별하며 동작을 설정해주면된다.

 

 

 

 

 

메뉴 아이템을 사용자가 만든 레이아웃으로 설정해주고 싶을 때는 따로 layout폴더에 xml 파일을 만들어 준다.(여기서는 search_layout.xml 만들어줌) 이렇게 xml 파일을 만들고 나면 아까만들어준 메뉴 xml파일에 item 항목에서 

 

app:actionLayout="@layout/search_layout"

 

위의 속성을 만들어준 레이아웃 xml파일로 지정해주면 그 레이아웃이 메뉴 아이템으로 보이게 된다.

 

 

 

 

 

위의 마지막으로 액티비티의 액션바를 없애주고 싶을 때는

 

ActionBar abar = getSupportActionBar();

        abar.hide();

 

이렇게 하면 된다.

 

 

 

 

 

결과화면

 

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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
 
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
    ListFragment fragment1 ;
    ViewerFragment fragment2 ;
 
    FragmentManager manager ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        manager = getSupportFragmentManager();
 
        fragment1 = (ListFragment) manager.findFragmentById(R.id.list_fragment) ;
        fragment2 = (ViewerFragment) manager.findFragmentById(R.id.viewer_fragment);
 
    }
 
    public void onImageChange(int index)
    {
        fragment2.setImage(index);
 
    }
 
}
 
 
cs

 

ListFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class ListFragment extends Fragment {
 
    MainActivity activity ;
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
 
        activity = (MainActivity) getActivity();
    }
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list, container, false);
 
        Button button = (Button) rootView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.onImageChange(0);
            }
        });
 
        Button button2 = (Button) rootView.findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.onImageChange(1);
            }
        });
 
        Button button3 = (Button) rootView.findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.onImageChange(2);
            }
        });
 
        return rootView ;
    }
}
 
cs

 

ViewerFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class ViewerFragment extends Fragment {
 
    ImageView imageView ;
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_viewer, container, false);
 
        imageView = (ImageView) rootView.findViewById(R.id.imageView);
 
        return rootView ;
    }
 
    public void setImage(int index)
    {
        if(index == 0)
        {
            imageView.setImageResource(R.drawable.ic_12);
        }
 
        else if(index == 1)
        {
            imageView.setImageResource(R.drawable.ic_15);
        }
 
        else if(index == 2)
        {
            imageView.setImageResource(R.drawable.ic_19);
        }
    }
}
 
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
<?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">
 
 
    <fragment
        android:id="@+id/list_fragment"
        android:name="com.example.boostcoursepractice.ListFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></fragment>
 
    <fragment
        android:id="@+id/viewer_fragment"
        android:name="com.example.boostcoursepractice.ViewerFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></fragment>
 
 
</LinearLayout>
cs

 

fragment_list.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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지1" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지2" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지3" />
</LinearLayout>
cs

 

fragment_viewer.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/ic_12" />
</LinearLayout>
 
 

 

프래그먼트는 앞선 글에서와 같이 코드에서 생성하는 방법이 있고 여기에서 처럼 xml내에서 직접 태그로 추가할 수도 있다. 여기서 만약 태그로추가하고 그 프래그먼트를 자바코드에서 직접 참조 하고 싶다면 일반적으로 쓰는 방법과 약간 달리

 

FragmentManager manager ;

manager = getSupportFragmentManager();

fragment1 = (ListFragment) manager.findFragmentById(R.id.list_fragment) ;

 

이렇게 프래그먼트 매저를 통해서 찾아야한다. 

 

여기서 들은 예시는 리스트 프래그먼트와 이미지뷰어 프래그먼트를 둘로 나우어 메인 액티비티에서 띄우고 리스트 프래그먼트의 버튼을 누르면 이미지 프래그먼트의 이미지를 바꿔주는데 이것 역시 중간에 액티비티를 거쳐서 바꿔줘야한다는 점을 잊지말자.

 

 

 

 

 

결과화면

 

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
package com.example.boostcoursepractice;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    Button button ;
    Button button2 ;
    MainFragment mainFragment;
    SubFragment subFragment;
    //FrameLayout frameLayout ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mainFragment = new MainFragment();
        subFragment  = new SubFragment();
 
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        //        //frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getSupportFragmentManager().beginTransaction().add(R.id.frame_layout, mainFragment).commit();
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();
            }
        });
 
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, subFragment).commit();
            }
        });
    }
 
    public void chageFragement(int n)
    {
        if(n == 0)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();
        }
        else if(n==1)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, subFragment).commit();
        }
    }
}
 
 
cs

 

MainFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
 
public class MainFragment extends Fragment {
 
    MainActivity activity ;
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
 
        activity = (MainActivity) getActivity();
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
 
        activity = null;
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_main, container, false) ;
        Button btn = (Button) rootView.findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.chageFragement(1);
            }
        });
        return rootView;
    }
}
 
cs

 

SubFragment

...더보기
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
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
 
import androidx.fragment.app.Fragment;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
 
public class SubFragment extends Fragment {
 
    MainActivity activity ;
 
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Toast.makeText(context, "attach 실행됨", Toast.LENGTH_LONG).show();
 
        activity = (MainActivity) getActivity();
    }
 
    @Override
    public void onDetach() {
        super.onDetach();
        Toast.makeText(getActivity(), "onDetach 실행됨", Toast.LENGTH_LONG).show();
 
        activity = null;
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Toast.makeText(getActivity(), "onCreateView 실행됨", Toast.LENGTH_LONG).show();
 
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_sub, container, false) ;
        Button btn = (Button) rootView.findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.chageFragement(0);
            }
        });
        return rootView;
    }
}
 
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
<?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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="시작" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/button"
        android:text="메뉴" />
 
    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/button">
        <!--
        <fragment
            android:id="@+id/fragment"
            android:name="com.example.boostcoursepractice.MainFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        -->
    </FrameLayout>
 
 
 
 
</RelativeLayout>
cs

 

fragment_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
<?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:background="@android:color/holo_orange_light"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="프래그먼트 1"
        android:textSize="40dp"
        />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="서브화면으로" />
 
 
</LinearLayout>
cs

 

fragment_sub.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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:background="@color/design_default_color_primary"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="프래그먼트 2"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메인화면으로" />
 
 
</LinearLayout>
cs

 

우선 프래그먼트를 이해하기 위해서는 아래의 그림을 이해해야 한다.

이처럼 액티비티를 전환하는 것은 시스템의 액티비티 매니저가 하지만 프래그먼트의 전환은 액티비티 안에 프래그먼트 매니저가 관리한다. 따라서 액티비티가 중심이 된다는 것을 잊지 말아야한다.

 

프래그먼트의 객체화는 

 

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

 

이 함수에서 이루어 진다.

 

 

 

 

메인액티비티에 나와 있는 것처럼 우선

 

mainFragment = new MainFragment();

subFragment  = new SubFragment();

 

이렇게 프래그먼트를 만들어주고 

 

getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, mainFragment).commit();

 

이런 함수를 통하여 액티비티 매니저를 이용하여 액티비티에 프래그먼트를 만들어 붙여 줘야 한다. 이 함수가 실행 될 때부터 프래그먼트의 수명주기가 시작이 된다.

 

또한 프래그먼트에서 다른 프래그먼트를 띄워 줄 때 프래그먼트 안에서 바로 띄워 줄 수 없고 해당 프래그먼트를 만들어준 액티비티를 통해 다른 프래그먼트를 띄워야 한다. (앞서 그림에서 설명한 이론 액티비티 중심) 따라서

 

activity = (MainActivity) getActivity();

 

이렇게 프래그먼트를 만들어준 액티비티를 얻고 

 

activity.chageFragement(1);

 

그 액티비티의 함수(액티비티 매니저를 통해 다른 프래그먼트를 띄울수 있게 정의함)를 실행하여 액티비티의 액티비티매니저를 통해 다른 프래그먼트를 띄울 수 있도록 해야 한다.

 

 

 

 

*****************************************************************************************8

마지막 참고로 프래그먼트를 그냥 xml 파일에서

 

 <fragment

            android:id="@+id/fragment"

            android:name="com.example.boostcoursepractice.MainFragment"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

 

이런식으로 코드가 아닌 태그로 추가할 수도 있다.

 

 

**중요1 : 프래그먼트에서 액티비티를 띄울 때 프래그먼트를 생성한 액티비티를 통해서 띄워야 된다. 따라서 프래그먼트에서 getActivity().startActivityResult()를 해야만 한다. 

 

**중요2 : 프래그먼트를 껐다가 다시 키긴보다는 transaction().hide() / transaction().show() 를 많이 이용하자 뭔가 다시 키면 리스트뷰나 뷰페이저가 다시 뜨지를 않는다.

 

 

 

 

결과화면 1

 

결과화면2

 

+ Recent posts