본문 바로가기

안드로이드

[Android] Custom Titlebar를 fragment로 만들기

1. 원하는 레이아웃 형태 정의

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout android:padding="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:id="@+id/app_toolbar"
    android:backgroundTint="@color/white"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageButton
        android:id="@+id/menu_button"
        android:src="@drawable/ic_baseline_menu_24"
        android:background="?android:selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

    <TextView
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <ImageButton
        android:id="@+id/search_button"
        android:src="@drawable/ic_baseline_search_24"
        android:background="?android:selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

2. Fragment를 상속받은 클래스 생성

class TitleBarFragment :Fragment(){
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view =  inflater.inflate(R.layout.custom_actionbar,container,false)
        view.menu_button.setOnClickListener { Log.d("fsd","1") }
        view.search_button.setOnClickListener { Log.d("fsd","asdf") }
        return view
    }
}

 

3. activity layout에 추가

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/TitleBar"
        class="com.drimase.pilgrimage.customView.TitleBarFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    ...


</LinearLayout>

 

리뷰

1에서 만든 레이아웃을 단순히 activity layout에 include하는 방법도 문제는 없어 보인다. 하지만 activity가 비대해질듯