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을 가지고 구별하여 기능의 구현한다.

 

 

 

 

결과화면

 

+ Recent posts