Android

[Android-Java] TabLayout 배경색 다르게 설정하기

기시미 2021. 3. 18. 18:45

Android에서 TabLayout에서 탭했을 때 배경색을 변경하는 코드는 따로 없기 때문에 drawable을 만들어주어야 합니다.

1. 기본 배경색

drawable > tab_background_unselected.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
</shape>

2. 선택된 탭 배경색

drawable > tab_background_selected.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#0070C0" />
</shape>

3. 최종 배경색 설정

drawable > tab_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/tab_background_selected" android:state_selected="true" />
    <item android:drawable="@drawable/tab_background_unselected" android:state_selected="false" android:state_focused="false" android:state_pressed="false" />
</selector>

4. TabLayout에 배경색으로 설정

app:tabBackground="@drawable/tab_background"

결과화면