Android

(스크랩 )android 탭 레이아웃 + 프레그먼트 예제 ( 프레임 레이아웃 사용)

Machine_웅 2021. 4. 2. 12:09
728x90
반응형
public class MainActivity extends FragmentActivity {

    TabLayout tabs;

    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();

        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment1).commit();

        tabs = findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setText("친구"));
        tabs.addTab(tabs.newTab().setText("채팅"));
        tabs.addTab(tabs.newTab().setText("더보기"));

        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Fragment selected = null;
                if(position == 0)
                    selected = fragment1;
                else if(position == 1)
                    selected = fragment2;
                else if(position == 2)
                    selected = fragment3;
                getSupportFragmentManager().beginTransaction().replace(R.id.container, selected).commit();
            }

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

            }

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

            }
        });

    }

}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="1dp"
        android:background="@android:color/background_light"
        app:tabMode="fixed"
        app:tabGravity="fill"
        app:tabTextColor="@color/colorPrimary"
        app:tabSelectedTextColor="@color/colorAccent" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_below="@id/tabs"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </FrameLayout>

</RelativeLayout>

ju-hy.tistory.com/54

 

TabLayout 사용법

TabLayout의 구성 Tab은 크게 Tab 버튼이 위치한 TabLayout과 화면이 바뀌는 아래쪽의 FrameLayout으로 구성된다. Tab 버튼을 눌렀을 때 아래쪽 부분화면이 바뀌어야 하므로 주로 FrameLayout 안에 Fragment를 넣..

ju-hy.tistory.com

 

728x90
반응형