일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 생활코딩
- 제이펍 출판
- 비주얼스튜디오 코드
- 한글입력 오류
- max MySQL
- 한글입력 씹힘
- 닐 스미스 지음
- python GUI 사용하기
- 자바스크립트 class
- max apache
- 맥 아파치
- 배열 분해 할당
- 객체지향
- 자바스크립트
- 기획자랑 사이좋게 지내고 싶다
- 제이쿼리연결
- SwiftUI 기반의 iOS 프로그래밍
- 한글잘림
- 자바스크립트 객체
- 한글입력 안됨
- jquery 사용하기
- 핵심만 골라 배우는 SwiftUI 기반의 iOS 프로그래밍
- python tkinter 인터페이스
- 황반석 옮김
- 객체
- 한글입력 잘림
- 맥 mysql
- 자바스크립트 객체 만들기
- 자바스크립트 배열 할당
- 블록 스코프
- Today
- Total
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 생활코딩
- 제이펍 출판
- 비주얼스튜디오 코드
- 한글입력 오류
- max MySQL
- 한글입력 씹힘
- 닐 스미스 지음
- python GUI 사용하기
- 자바스크립트 class
- max apache
- 맥 아파치
- 배열 분해 할당
- 객체지향
- 자바스크립트
- 기획자랑 사이좋게 지내고 싶다
- 제이쿼리연결
- SwiftUI 기반의 iOS 프로그래밍
- 한글잘림
- 자바스크립트 객체
- 한글입력 안됨
- jquery 사용하기
- 핵심만 골라 배우는 SwiftUI 기반의 iOS 프로그래밍
- python tkinter 인터페이스
- 황반석 옮김
- 객체
- 한글입력 잘림
- 맥 mysql
- 자바스크립트 객체 만들기
- 자바스크립트 배열 할당
- 블록 스코프
- Today
- Total
java,javascript,android,php,sql,공부용,메모용
안드로이드 스튜디오 상단탭 만들기, 하단탭 만들기 AppBarLayout, Toolbar, TabLayout / Android Studio / 안드로이드 앱만들기 29 본문
안드로이드 스튜디오 상단탭 만들기, 하단탭 만들기 AppBarLayout, Toolbar, TabLayout / Android Studio / 안드로이드 앱만들기 29
yy_dd2 2021. 3. 21. 18:31상단 탭 만들기
탭은 내비게이션 위젯이라고도 한다 상단탭 하단탭으로 구분됨 최근에 하단탭을 더 많이 사용함
상단탭 만들어보기
1. SampleTab 프로젝트생성
- 패키지 변경하라고함 난안함
2. activity_main.xml의 Design 탭 선택
팔레트에서 containers -> AppBarLayout 다운로드
![]() |
![]() |
머티리얼 라이브러리를 추가하면 이 정보는 build.gradle 파일 안에 들어간다.
build.gradle 파일에 내용이 추가되어 있다.
build.gradle 파일에 (Project: SampleTab) 과 (Module: app) 가 있다.
build.gradle (Module:app) 파일을 비교해보자
비교하기
설치 전
apply plugin: 'com.android.application'
//.../생략/
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
설치 후
apply plugin: 'com.android.application'
//.../생략/
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.android.material:material:1.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
implementation 'com.google.android.material:material:1.3.0' 이부분이 추가되었다
이렇게 디자인의 팔레트에서 다운받으면 머티리얼 라이브러리에 추가된다.
추가된 라이브러리를 XML 레이아웃에서 이제 정의할 수 있다.
3. 액션바 정의하기 activity_main.xml
순서
<CoordinatorLayout>
<AppBarLayout>
<Toolbar>
</Toolbar>
<TabLayout>
</TabLayout>
</AppBarLayout>
<FrameLayout>
</FrameLayout>
<coordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:elevation="1dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="@+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="타이틀"
android:textAppearance="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title" />
</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:tabGravity="fill"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/colorPrimary" />
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
코드내용 확인해보면
<CoordinatorLayout> <!-- <androidx.coordinatorlayout.widget.CoordinatorLayout -->
// 액션바 영역을 포함한 전체 화면의 위치 잡아준다
<AppBarLayout> <!-- <com.google.android.material.appbar.AppBarLayout -->
// CoordinatorLayout 안에 AppBarLayout이 다른 레이아웃을 두면
// 간격이나 위치가 자동으로 결정됨
// AppBarLayout은 액션바 이안에는 Toolbar가 들어갈수있음
// 탭 추가시 TabLayout 추가 가능
<Toolbar> <!-- <androidx.appcompat.widget.Toolbar -->
</Toolbar>
<TabLayout> <!-- <com.google.android.material.tabs.TabLayout -->
</TabLayout>
</AppBarLayout> </com.google.android.material.appbar.AppBarLayout>
<FrameLayout> <FrameLayout>
</FrameLayout> </FrameLayout>
// FrameLayout을 포함해 화면 구성도 가능함
<coordinatorLayout> </androidx.coordinatorlayout.widget.CoordinatorLayout>
디자인으로 추가해봐야겠다 나중에 더 편하고 빠르게 만들수있게!
-> 그런데 해보니까 코드를 작성하는게 빠르겠다는 생각이 들었다 그래도 확인해보기
![]() |
![]() |
이렇게 하고나니 코드가 좀 다르다 그리고 추가해야하는 부분이 있다
우선 지금 상태의 코드
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="192dp">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</androidx.appcompat.widget.Toolbar>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="타이틀" />
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
여기에 TextView를 Toolbar 안에 넣어줘야하는데 Component Tree 안에서는 안된다
잘라내기해서 붙여넣기 AppBarLayout / Toolbar / TextView 설정
AppBarLayout theme 추가
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
Toolbar theme 추가
똑같은 방식으로 찾아서 추가
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
TextView textAppearance 속성 추가
TextView textAppearance 속성은?
텍스트가 화면에 표시될 때 모양을 지정하는 속성중 하나다 "textColor", "typeface", "textSize", "textStyle"같은게있지만이모든걸 시스템에서 미리 정해진 형식에 따라 한번에 설정하도록 만들어주는 속성이다
android:textAppearance - color, typeface, size, style을 한번에 설정. > 프레임워크에 정의된 값을 지정. > R.attr에 "textAppearanceXXX" 형식으로 명명된 값 사용.
사용 방법
- 속성에 "textAppearanceXXX" 값을 지정
- 단, 속성에 값을 지정할 때, 스타일 속성 리소스 참조 형식("?android:attr/textAppearanceXXX")을 사용해야 한다
책에서 나오는
android:textAppearance="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
은 자동완성이 안된데 이유는 모르겠다 그냥 적어줬다
이거 적으면 오류가 나서 그냥 책에있는대로했다
TabLayout 속성 추가
android : id, background, elevation
id와 background는 아는데 elevation 설정을 모른다
elevation은 그림자, 입체감을 주는 설정인데 image에 자주 사용한다고한다.
여기서는 디자인툴에 속성에 없기 때문에 직접 작성해준다
app : tabGravity, tabMode, tabSelectedTextColor, tabTextColor
속성 | 설명 |
tabGravity | - tab의 정렬 방식에 대한 옵션입니다. "center" 탭을 가운데 정렬하여 표시합니다. "fill" 탭의 너비를 동일하게 정렬하여 표시합니다. |
tabMode | - tab의 표시 방식에 대한 옵션입니다. "fixed" 모든 탭을 화면에 표시되도록 설정합니다. "scrollable" 탭이 화면을 넘어갈 시 스크롤이 되도록 설정합니다. |
tabTextColor | - tab안의 Text의 색상을 지정합니다. |
tabSelectedTextColor | - tab 선택 시에, tab안의 Text의 색상을 지정합니다. |
tabIndicatorHeight | - tab 하단의 Indicator의 높이를 지정합니다. |
tabIndicatorColor | - tab 하단의 Indicator의 색상을 지정합니다. |
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/colorPrimary"
android:elevation="10dp"/>
FrameLayout 속성 추가
app:layout_behavior
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
디자인툴로 적용한 코드 전문
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<TextView
android:id="@+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="타이틀"
android:textAppearance="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title" />
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/colorPrimary"
android:elevation="10dp"/>
</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>
</androidx.constraintlayout.widget.ConstraintLayout>
4. 프래그먼트 화면 만들기 3개
Fragment_1.java
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
Fragment_2.java
public class Fragment2 extends Fragment {
....생략
return inflater.inflate(R.layout.fragment_1, container, false);
Fragment_3.java 까지생성
![]() |
![]() |
![]() |
5. 액션바 설정하고 프래그먼트 객체 생성하기
MainActivity.java
package com.togapp.tab;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
Fragment1 fragment1;
Fragment2 fragment2;
Fragment3 fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
// 꼭 이걸로 설정해줘야함 import androidx.appcompat.widget.Toolbar;
// setSupportActionBar() 액티비티에 디폴트로 만들어진 액션바가 없을 경우 동작함
// 프로젝트가 만들어질때 메인 액티비티에는 자동으로 액션바가 만들어진다 테바를 액션바가 들어있는 설정으로 되어있기 때문이다
// 액티비티에 설정된 테마를 변경해보자
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
fragment1 = new Fragment1();
fragment2 = new Fragment2();
fragment3 = new Fragment3();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
}
}
setSupportActionBar() 액티비티에 디폴트로 만들어진 액션바가 없을 경우 동작한다
프로젝트가 만들어질때 메인 액티비티에는 자동으로 액션바가 만들어진다
테마를 액션바가 들어있는 설정으로 되어있기 때문이다 액티비티에 설정된 테마를 변경해보자
6. 프로젝트 테마 설정변경
/app/res/values 폴더 안에 있는 styles.xml 파일
AppTheme 라는 name 속성 값을 가진 <style> 태그가 있다 parent 속성 값은 API 정의한 테마 중 하나로 지정되어있다
AndroidManifest.xml 파일에서 <application> <activity> 태그에 지정되어 있는 액티비티 테마로 설정됨
기존코드
<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>
</resources>
아래처럼 변경
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
.NoactionBar
이렇게하면 액티비티가 만들어질때 액션바가 자동으로 만들어지지 않는다
setSupportActionBar() 메서드를 호출해 직접 액션바를 설정한다 (위에서 MainActivity.java 에 설정함)
7. 첫번째 프래그먼트가 보이도록 코드 작성
// 생략
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
TabLayout tabLayout = findViewById(R.id.tabs);
// addTab() 메서드는 탭 버튼을 추가한다
tabLayout.addTab(tabLayout.newTab().setText("통화기록"));
tabLayout.addTab(tabLayout.newTab().setText("스팸기록"));
tabLayout.addTab(tabLayout.newTab().setText("연락처"));
// 추가된 탭버튼을 눌렀을때 각각의 FrameLayout에 프래그먼트 화면이 보이도록 설정
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
Log.d("MainActivity","선택된 탭 : " + position);
Fragment selected = null;
//선택된 Tab객체의 위치값(왼족 처음부터 0,1,2....순으로 됨)
if (position == 0) {
selected = fragment1;
} else if (position == 1) {
selected = fragment2;
} else if (position == 2) {
selected = fragment3;
}
/*switch( position ) {
case 0: //가장 왼쪽 Tab 선택(Analog)
//MainActivity가 보여 줄 View를
//res폴더>>layout폴더>>fragment_1.xml 로 설정
selected = fragment1;
//setContentView(R.layout.fragment_1);
break;
case 1: //두번째 Tab 선택(Digital)
//MainActivity가 보여 줄 View를
//res폴더>>layout폴더>>fragment_2.xml 로 설정
selected = fragment2;
//setContentView(R.layout.fragment_2);
break;
case 2: //세번째 Tab 선택(Calendar)
//MainActivity가 보여 줄 View를
//res폴더>>layout폴더>>fragment_3.xml 로 설정
selected = fragment3;
//setContentView(R.layout.fragment_3);
break;
}*/
getSupportFragmentManager().beginTransaction().replace(R.id.container,selected).commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
8. 실행 결과확인
코드에 Log.d("MainActivity","선택된 탭 : " + position); 부분으로 선택된 탭이 어느부분인지 확인가능
기억하기
setSupportActionBar()
액티비티에 디폴트로 만들어진 액션바가 없을 경우 동작한다
프로젝트가 만들어질때 메인 액티비티에는 자동으로 액션바가 만들어진다
/app/res/values 폴더 안에 있는 styles.xml 파일
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
이렇게하면 액티비티가 만들어질때 액션바가 자동으로 만들어지지 않는다
setSupportActionBar() 메서드를 호출해 직접 액션바를 설정한다
.addTab
TabLayout tabLayout = findViewById(R.id.tabs);
// addTab() 메서드는 탭 버튼을 추가한다
tabLayout.addTab(tabLayout.newTab().setText("통화기록"));
tabLayout.addTab(tabLayout.newTab().setText("스팸기록"));
tabLayout.addTab(tabLayout.newTab().setText("연락처"));
.addTab 해서 만들어진 탭은 만들어지는 순서대로 position의 값이 결정된다 0,1,2,3~ 순
하단탭 만들어보기 ( 21-03-22 )
BottomNavigationView 위젯으로 만들 수 있다.
위젯은 머티리얼 라이브러리를 사용한다 외부라이브러리를 추가하는 과정을 한다.
팔레트에서 BottomBavigationView 다운로드한다.
1. SampleTab2 프로젝트 생성
2. /app/res
- menu 폴더 생성
- menu_bottom.xml 파일 생성 [menu 폴더에서 우클릭 New - Menu Resource File ]
3. SampleTab 위에 상단탭 만들어보기 프로젝트에서
Fragment1, 2, 3 xml파일과 java 파일을 모두 복사해서 각각의 layout폴더와 java폴더에 붙여넣는다
4. item_color.xml 파일 [ drawable 폴더에 생성 ]
activity_main.xml 파일을 작성할때 @drawable/item_color 를 쓰는데
책에는 item_color.xml 파일에 대한 내용은 없다. 그래서 파일 생성 안하고 쓰면 오류남
책에있는 컬러가 넘 구려서 맘대로 바꿧다
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#EBDA75" />
<item android:color="#CFD8DC" />
</selector>
5. menu_bottom.xml 코드 추가
- 디자인 툴에 쉽게 나와있어서 디자인툴에서 씀
<?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:id="@+id/tab1"
android:enabled="true"
android:icon="@android:drawable/ic_dialog_email"
android:title="이메일"
app:showAsAction="ifRoom" />
<item
android:id="@+id/tab2"
android:icon="@android:drawable/ic_dialog_info"
android:title="정보"
app:showAsAction="ifRoom" />
<item
android:id="@+id/tab3"
android:enabled="true"
android:icon="@android:drawable/ic_dialog_map"
android:title="위치"
app:showAsAction="ifRoom" />
</menu>
"showAsAction" 속성
아이템을 "액션으로 보여줄 때" 속성이다
값에 따라서 어떻게 표시될지 결정됨
showAsAction
showAsAction 속성값 | 설명 |
always | 아이템을 항상(always) 앱바(App Bar)의 액션으로 표시 never와 ifRoom보다 우선, 공간이 없으면 표시하지 않음 |
never | 아이템을 앱바의 액션으로 표시하지 않고 오버플로우 메뉴에 바로 표시 |
ifRoom | 공간이 있으면 ifRoom 앱바의 액션으로 표시한다 공간이 없다면 오버플로우 메뉴에 표시 |
withText | 아이템을 앱바의 액션으로 표시할 때 텍스트와 같이 표시 단, 아이콘과 텍스트를 같이 표시할 공간이 없으면 텍스트만 표시 |
collapseActionView | 아이템 커스텀 액션 뷰가 지정된 경우, 축소된 형태로 표시 |
6. activity_main.xml 파일 코드 작성
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!--<com.google.android.material.bottomappbar.BottomAppBar/>-->
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:itemBackground="@color/colorPrimary"
app:itemIconTint="@drawable/item_color"
app:itemTextColor="@drawable/item_color"
app:menu="@menu/menu_bottom"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
주의할점 책에서 BottomNavigetionView 쓰라고했는
com.google.android.material.bottomappbar.BottomAppBar 를 사용하면 오류가 난다
com.google.android.material.bottomnavigation.BottomNavigetionView 를 사용해야한다.
7. MainActivity.java 코드 작성
package com.togapp.tab;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
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);
// 생성자 만들기
fragment1 = new Fragment1();
fragment2 = new Fragment2();
fragment3 = new Fragment3();
// container(FrameLayout)에 fragment1이 먼저 보이도록 commit() 실행
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.tab1:
Toast.makeText(getApplicationContext(),"첫 번째 탭 선택",Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
return true;
case R.id.tab2:
Toast.makeText(getApplicationContext(),"두 번째 탭 선택", Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment2).commit();
return true;
case R.id.tab3:
Toast.makeText(getApplicationContext(),"세 번째 탭 선택", Toast.LENGTH_LONG).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment3).commit();
return true;
}
return false;
}
});
}
}
'모바일 > 안드로이드앱' 카테고리의 다른 글
바로가기 메뉴 만들기 탭메뉴 NavigationDrawer / Android Studio / 안드로이드 앱만들기 31 (0) | 2021.04.24 |
---|---|
ViewPager2 뷰페이저 만들기 / Android Studio / 안드로이드 앱만들기 30 (0) | 2021.04.03 |
안드로이드 스튜디오 프로젝트명 변경 (패키지명 아님) / Android Studio / 안드로이드 앱만들기 (0) | 2021.03.21 |
안드로이드 앱 액션바, 옵션 메뉴, 컨텍스트 메뉴 / Android Studio / 안드로이드 앱만들기 28 (0) | 2021.03.20 |
안드로이드앱 프래그먼트 수명주기 상태메서드 onAttach() / Android Studio / 안드로이드 앱만들기 27 (0) | 2021.03.20 |