본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Android 화면 구성 기능(디자인- xml 과 java로 제어)

Android Studio Material Design (Navigation Drawer, Toolbar, AppBar Layout, TabLayout)

by 차누감 2019. 9. 30.

◎Material Design : Gogle 디자인 가이드 라인

Navigation Drawer

Toolbar

AppBar Layout, TabLayout

 

 

<최종 실행 화면>

 

 

제목 줄부터 없애자.

제목바가 없어진것을 확인 할 수 있다.

Drawer layout을 먼저 만들고 화면을 꾸미자. (1.전면은 Linear layout 2.사이드 Navigation View)

 

전면 대충 Linear View만 만들고

일단 사이드 메뉴를 위해 라이브러리 추가하자

주황색 네모의 버전 숫자가 다르면 똑같이 맞춰주자. 안그러면 동작이 안될 수 있다.
미리보기로 사이드 메뉴가 생성된 것을 알 수있다.

이제 사이드 메뉴(헤더, 메뉴)의 헤더를 만들어보자.

방금 전에 만든 헤더 레이아웃을 추가하면 이제 사이드 메뉴의 헤더가 나타나는 것을 확인할 수 있다.

이제 사이드 메뉴(헤더, 메뉴)의 헤더를 만들어보자.

앱바 안에 툴바가 들어 간 것을 볼 수 있지만 .글씨가 검은색이라 테마를 새로 만들겠다.

목록 아이콘 삼선을 만들자.

 

삼선 흰색으로

이제 메뉴 목록에 리스너 추가하고, 목록을 누르면 사이드 메뉴창이 자동으로 닫히게 하자.

이제 툴바 밑에 Tab을 추가하자.

 

탭 제어는 자바에서 

탭의 글씨 색(그냥, 선택됐을 때)을 바꾸자. 

이제 Fragment 3개를 만들 것이다.

]

 

fragment_page1을 복사해서 layout에 붙여넣자. ( .xml이름-> page2, page3 / 버튼 이름 "PAGE2", "PAGE3")

 

나머지 Page2,3은 Page1을 복사해서 붙여 넣자. ( 

(경로 주의 !! : java폴더 바로 밑에 있는 폴더에 붙어넣자 아래 사진은 잘못 넣어서, 나중에 다시 옮겼다.)

[MainActivity.java와 같은 폴더에 넣자!!]

위 사진은 잘못 붙여넣었다. java폴더 바로 밑에 있는 폴더에 붙어넣자

다 복붙 하고 Page2,3.java에서 inflate(R.layout.fragment_page1 <-만 페이지에 맞게 변경)

 

이제 해당 페이지를 화면에 보이도록 adapter를 만들자.

 

FragmentPagerAdapter를 상속받는다.
.java 파일은 5개 만들어져 있어야 한다.
아래에 Pager는 이제 페이지가 -> 드래그로 넘어간다. 하지만 탭과 연동이 안된다.

이제 Pager와 Tab을 연동해보자.

그래서 기존에 만든 탭은 의미가 없다!!!

만약에 탭에 아이콘도 넣고 싶다면 이 코드를 써주자.

빨간색 네모 아래, 네비게이션 뷰 아이템 선택 리스너는 그냥 써준것이다. 기능을 하는 코드는 없음. 동작하고 싶은 기능이 있다면 저 case문에 넣자.

 

Tab과 Pager가 연동이 된다.

그리고 이제 서브 타이틀을 추가해보겠다.

Title 제목 밑에 작은 subTilte이 보일 것이다.

우측 상단에 옵션 메뉴를 만들자.

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
53
54
55
56
57
58
59
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout_drawer"
    tools:context=".MainActivity">
 
<!--    1. 콘텐츠 영역-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
 
<!--        AppBar도 material 라이브러리가 있어야 사용 가능하다.-->
<!--        AppBar는 기존 제목 색을 갖는다. 그래서 Toolbar에 색상이 입혀졌다.-->
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.Appbar">
 
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize">
            </androidx.appcompat.widget.Toolbar>
 
                android:id="@+id/layout_tab"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabTextColor="@color/white"
                app:tabSelectedTextColor="#FF8800"
                app:tabIndicatorColor="#FF8800"
                app:tabIndicatorHeight="4dp"
                app:tabMode="fixed"
                app:tabGravity="fill">
 
 
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
 
    </LinearLayout>
 
<!--    2. 왼쪽 사이드 메뉴-->
        android:id="@+id/nav"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer_menu"/>
 
 
 
 

drawer_header.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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="#ff8800"
    android:padding="8dp">
 
    <ImageView
        android:id="@+id/header_iv"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@mipmap/ic_launcher"/>
    <TextView
        android:id="@+id/header_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:layout_below="@id/header_iv"
        android:layout_marginTop="8dp"/>
 
</RelativeLayout>
 
 

fragment_page1.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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"
android:padding="16dp">
 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="PAGE 1"/>
 
</LinearLayout>
 
 

fragment_page2.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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"
android:padding="16dp">
 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="PAGE 2"/>
 
</LinearLayout>
 
 

fragment_page3.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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"
android:padding="16dp">
 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="PAGE 3"/>
 
</LinearLayout>
 
 

menu (drawer_menu, option)

drawer_menu.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
 
    <item android:id="@+id/menu_aa"
        android:title="aa"
        android:icon="@mipmap/ic_launcher"/>
 
    <item android:id="@+id/menu_bb"
        android:title="bb"/>
 
    <item android:id="@+id/menu_cc"
        android:title="cc"/>
 
</menu>
 
 

 

option.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
 
    <item android:id="@+id/menu_search"
        android:title="search"
        android:icon="@android:drawable/ic_menu_send"
        app:showAsAction="always"/>
 
    <item android:id="@+id/menu_save"
        android:title="save"
        app:showAsAction="never"/>
    <item android:id="@+id/menu_del"
        android:title="delete"
        app:showAsAction="never"/>
 
</menu>
 
 

 


colors.xml 코드

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
 
    <color name="white">#FFFFFF</color>
</resources>
 
 
 

styles.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
<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" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 
<!--    앱바에 적용될 스타일 테마 -->
    <style name="AppTheme.Appbar">
        <item name="titleTextColor">@color/white</item>
<!--        액션바의 메뉴아이템들 색상-->
        <item name="colorControlNormal">@color/white</item>
        <item name="subtitleTextColor">@color/white</item>
    </style>
 
</resources>
 
 
 

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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
 
import androidx.annotation.NonNull;
 
 
 
public class MainActivity extends AppCompatActivity {
 
    NavigationView navigationView;
    DrawerLayout  drawerLayout;
    ActionBarDrawerToggle drawerToggle;
 
    TabLayout tabLayout;
 
    ViewPager pager;
    MyAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //Toolbar를 액션 바로 대체하기
        Toolbar  toolbar= findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        navigationView=findViewById(R.id.nav);
        navigationView.setItemIconTintList(null);// 사이드 메뉴에 아이콘 색깔을 원래 아이콘 색으로
 
        drawerLayout=findViewById(R.id.layout_drawer);
        drawerToggle=new ActionBarDrawerToggle(this, drawerLayout,toolbar,R.string.app_name,R.string.app_name);
        drawerLayout.addDrawerListener(drawerToggle);//누를때마다 아이콘이 팽그르 돈다.
        drawerToggle.syncState();// 삼선 메뉴 추가
 
        tabLayout=findViewById(R.id.layout_tab);
        //탭버튼(Tab객체) 생성
//        TabLayout.Tab tab=null;
//        tab=tabLayout.newTab();
//        tab.setText("Home");
        //tab=tabLayout.newTab().setText("Home"); // 위 두줄을 한줄로
       // tab.setIcon(R.mipmap.ic_launcher); //요약된 한 줄에 아이콘 추가하여 한줄로
//        tab=tabLayout.newTab().setText("Home").setIcon(R.mipmap.ic_launcher);
//        tabLayout.addTab(tab);
//        tab=tabLayout.newTab().setText("Theme").setIcon(R.mipmap.ic_launcher);
//        tabLayout.addTab(tab);
//        tab=tabLayout.newTab().setText("Talk").setIcon(R.mipmap.ic_launcher);
//        tabLayout.addTab(tab);
 
        pager=findViewById(R.id.pager);
        adapter= new MyAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
 
        //TabLayout과 ViewPager를 연동
        tabLayout.setupWithViewPager(pager);
        //주의!  View페이저와 연동하게 되면
        //위에 직접 코드로 추가했던 Tab객체는 무시됨.
        //대신 ViewPager에서 탭버튼의 글씨를 설정
 
        //아이콘을 삽입하고 싶다면..
       // tabLayout.getTabAt(0).setIcon(R.mipmap.ic_launcher);
 
        //제목줄에 서브제목 설정하기
        getSupportActionBar().setSubtitle("Home");
 
        //탭 변경 리스너
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                getSupportActionBar().setSubtitle(tab.getText());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
 
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
 
            }
        });
 
        //네비게이션뷰에 아이템선택 리스너 추가
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.menu_aa:
                        break;
                    case R.id.menu_bb:
                        break;
                    case R.id.menu_cc:
                        break;
                }
 
                //Drawer Nav 닫기
                drawerLayout.closeDrawer(navigationView);
                return false;
            }
        });
 
    }//onCreate()..
 
    //옵션메뉴 만들어주는 메소드
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.option, menu);
        return super.onCreateOptionsMenu(menu);
    }
 
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //여기에 옵션이 클릭됐을 때 하는 동작을 기재
        switch(item.getItemId()){
            case R.id.menu_search:
                Toast.makeText(this"menu_search", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_save:
                Toast.makeText(this"menu_save", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_del:
                Toast.makeText(this"menu_delete", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}//MainActivity class..
 
 
 

MyAdapter.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
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
public class MyAdapter extends FragmentPagerAdapter {
 
    Fragment[] fragments= new Fragment[3];
    String[] pageTitles= new String[]{"Home""Theme""Talk"};
    public MyAdapter(@NonNull FragmentManager fm) {
        super(fm);
 
        fragments[0]=  new Page1Fragment();
        fragments[1]=  new Page2Fragment();
        fragments[2]=  new Page3Fragment();
    }
    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }
    @Override
    public int getCount() {
        return fragments.length;
    }
 
    //뷰페이저와 연동된 텝레이아웃의 탭버튼들의
    //글씨를 리턴해주는 메소드
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return pageTitles[position];
    }
}
 
 
 

Page1Fragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
 
public class Page1Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_page1, container,false);
        return view;
    }
}
 
 
 

Page2Fragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
 
public class Page2Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_page2, container,false);
        return view;
    }
}
 
 
 

Page3Fragment.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
 
public class Page3Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_page3, container,false);
        return view;
    }
}
 
 
 

댓글