DEV 💙/Android

[Android] ViewPager와 Fragment 이용하여 TabLayout 만들기

DONI. 2019. 2. 4. 20:27
반응형



인스타그램이나 카카오톡과 같은 하단 탭메뉴 적용하기!


인스타그램 탭 메뉴



탭메뉴를 이용해서 페이지 이동이 가능하다


만드는 방법은 Tablayout을 이용하는 것, BottomNavigationLayout을 이용하는 방법 등등 여러가지가 있지만

이번에는 Tablayout을 이용하여 하단 탭메뉴를 구성하고 ViewPager와 Fragment로 화면을 구성하는 방법으로 시작!



먼저 Tablayout은 안드로이드에서 제공되는 design 서포트 라이브러리에 포함되어 있기때문에

사용을 위해서는 dependency를 추가해주어야 한다



1 gradle(Module:app) 에 dependency를 추가한다

implementation 'com.android.support:design:(appcompat version)'


dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'


implementation 'com.android.support:design:28.0.0' //Tablayout
}


다른 블로그를 보면 'implementation - '이 아니고 'compile - ' 으로 되어있는 것도 있던데

안드로이드 스튜디오3로 업그레이드 되면서 compile -> implementation / Api로 변경된 듯 하다!



2 main activity에 TabLayout과 ViewPager를 추가해준다


▶ activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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">


<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_centerInParent="true">

<!--ViewPager TabLayout-->

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>


<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
app:tabIndicatorGravity="top"
app:tabIndicatorColor="#FFFFFF"
app:tabGravity="fill"
app:tabMode="fixed"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_alignParentBottom="true" />

<!--ViewPager TabLayout end-->


</android.support.percent.PercentRelativeLayout>

</android.support.design.widget.CoordinatorLayout>


인스타그램 등과 같이 아랫쪽에 TabLayout을 위치시켰다



TabLayout에서 사용되는 속성을 정리하면 다음과 같다


XML Attributes 

Description 

 design:tabGravity

탭의 정렬 방식 선택

fill : 너비를 모두 같게 표시

center : 가운데 정렬하여 표시 

 design:tabMode

탭의 표시 방식을 선택

Fixed : 모든 탭을 한번에 표시

Scrollable : 일부 탭만 표시. 나머지 스크롤

 design:tabIndicatorColor

현재 선택된 탭에 대한 색 지정

 design:tabTextColor

탭에 적용할 기본 텍스트 색 지정

 design:tabSelectedTextColor

 현재 선택된 탭의 텍스트 색 지정



3  탭으로 사용할 Fragment를 생성한다


▶ TabFragment1.java

package com.test.frag.test;

import ...

public class TabFragment1 extends Fragment {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment1, null);

return view;
}
}


▶ tab_fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Fragment1"/>

</LinearLayout>


▲ 이 부분에서 각 Fragment에서 보여줄 화면, 기능을 구성한다



4 TabPagerAdapter를 생성한다

FragmentStatePagerAdapter를 상속받는다. 탭이 변할 때 마다 해당 탭의 position을 받아서 Fragment를 전환해준다


▶ TabPagerAdapter.java

package com.test.frag.test;

import ...

public class TabPagerAdapter extends FragmentStatePagerAdapter {

// Count number of tabs
private int tabCount;

public TabPagerAdapter(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}

@Override
public Fragment getItem(int position) {

// Returning the current tabs
switch (position) {
case 0:
TabFragment1 Fragment1 = new TabFragment1();
return Fragment1 ;
case 1:
TabFragment2 Fragement2 = new TabFragment2();
return Fragement2 ;
case 2:
TabFragment3 Fragment3 = new TabFragment3();
return Fragment3 ;
default:
return null;
}
}

@Override
public int getCount() {
return tabCount;
}
}



5 MainActivity에서 ViewPager와 TabLayout을 생성 / 초기화한다

그리고 각 ViewPageer와 TabLayout에 리스너를 달아준다


▶ MainActivity.java

package com.test.frag.test;

import ...
public class MainActivity extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initializing the TabLayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.tab_!));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.tab_2));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.tab_3));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

// Initializing ViewPager
viewPager = (ViewPager) findViewById(R.id.pager);

// Creating TabPagerAdapter adapter
TabPagerAdapter pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

// Set TabSelectedListener
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
})
;
}
}


여기서 하단 탭에 설정해줄 아이콘을 넣을 수 있는데

Initializing the TabLayout 부분을 보면 나는 setIcon을 이용하여 이미지를 넣어줬따!


setText()를 이용하면 텍스트로 설정하여 이용할 수 있다

(ex. tabLayout. addTab(tabLayout.newTab().setText("1번 탭")); )




반응형