본문으로 바로가기


안녕하세요. PEACE- 에요.

안드로이드 스터디의 [다섯 번째] 글이네요.


오늘은 탭 버튼을 구현에 대해 포스팅하겠습니다.


# 수정

[2019.05.06] fragment_fragment2.xml -> " 빠진 부분 채움



1. Tab Button


요즘 Tab을 이용한 앱 구성이 많이 활발해졌습니다. 페이스북이나 인스타그램, 카카오톡만 해도 탭 버튼을 이용한 화면 구성 법을 사용하고 있습니다. 이 앱들의 소스코드에서는 어떤 방식으로 Tab을 구현하였는지는 알지 못하나 저희도 Tab을 쉽게 구현 할 수 있다는 것은 확실합니다!


[그림 1] 카카오톡과 인스타그램의 탭 버튼 구성


Tab버튼을 구성하는데는 여러가지의 방법이 있습니다. 이 포스팅에서는 아래 그림과 같이 Activity의 버튼(보여줄 화면의 수 만큼)과 나머지 영역에 framLayout이라는 위젯을 배치하여 전체적인 레이아웃을 구성하고, 버튼 선택 시 framLayout에 원하는fragment를 띄우는 방식으로 구현할 것 입니다.



[그림 2] FrameLayout과 button을 이용한 탭 버튼 구성






2. 소스코드와 구현화면


[그림 3] 구현 화면





[그림 4] 소스 리스트


핵심**activity_main.xml : 탭 버튼과 프레임레이아웃 구성

핵심**MainActivity.class : 탭 버튼 클릭을 통해 프레임레이아웃에 프래그먼트를 띄움

fragment_fragment1.xml : 프래그먼트1 레이아웃
fragment_fragment2.xml : 프래그먼트2 레이아웃

Fragment1.class : 프래그먼트1
Fragment2.class : 프래그먼트2




#소스코드


activity_main.xml

<?xml version="1.0"
encoding="utf-8"?>
<RelativeLayout 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="peace.tabbutton.MainActivity">


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/linearLayout" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:id="@+id/linearLayout">

<Button
android:layout_weight="1"
android:id="@+id/bt_tab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 1"/>

<Button
android:layout_weight="1"
android:id="@+id/bt_tab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 2"/>

</LinearLayout>

</RelativeLayout>


MainActivity.class
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private final int FRAGMENT1 = 1;
private final int FRAGMENT2 = 2;

private Button bt_tab1, bt_tab2;

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

// 위젯에 대한 참조
bt_tab1 = (Button)findViewById(R.id.bt_tab1);
bt_tab2 = (Button)findViewById(R.id.bt_tab2);

// 탭 버튼에 대한 리스너 연결
bt_tab1.setOnClickListener(this);
bt_tab2.setOnClickListener(this);

// 임의로 액티비티 호출 시점에 어느 프레그먼트를 프레임레이아웃에 띄울 것인지를 정함
callFragment(FRAGMENT1);


}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bt_tab1 :
// '버튼1' 클릭 시 '프래그먼트1' 호출
callFragment(FRAGMENT1);
break;

case R.id.bt_tab2 :
// '버튼2' 클릭 시 '프래그먼트2' 호출
callFragment(FRAGMENT2);
break;
}
}

private void callFragment(int frament_no){

// 프래그먼트 사용을 위해
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

switch (frament_no){
case 1:
// '프래그먼트1' 호출
Fragment1 fragment1 = new Fragment1();
transaction.replace(R.id.fragment_container, fragment1);
transaction.commit();
break;

case 2:
// '프래그먼트2' 호출
Fragment2 fragment2 = new Fragment2();
transaction.replace(R.id.fragment_container, fragment2);
transaction.commit();
break;
}

}


}


fragment_fragment1.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="peace.tabbutton.Fragment1">

<!-- TODO: Update blank fragment layout -->
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="프래그먼트 1" />

</FrameLayout>


Fragment1.class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* A simple {@link Fragment} subclass.
*/
public class Fragment1 extends Fragment {


public Fragment1() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}

}


fragment_fragment2.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="peace.tabbutton.Fragment1">

<!-- TODO: Update blank fragment layout -->
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="프래그먼트 2" />


</FrameLayout>


Fragment2.class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
* A simple {@link Fragment} subclass.
*/
public class Fragment2 extends Fragment {


public Fragment2() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}

}













# 참고 사항
본 포스팅 내용은 '탭 뷰' 구현에 있어서 항상 올바른 방향을 제시하는 것은 아님을 미리 말씀드립니다.
개발 목적에 따라 다르며 오픈소스를 참고하여 '탭 뷰'를 구현하는 것도 시도해 보시길 추천합니다.
수 많은 방법 중 하나의 '예'일 뿐 입니다.


















댓글공감은 환영입니다.