티스토리 뷰

728x90
반응형
SMALL
반응형

안녕하세요, 여러분! 이번에는 ToDo 앱의 화면을 구성하는 예제를 통해 프래그먼트(Fragment)를 자세히 살펴보겠습니다. ToDo 앱은 많은 사용자들에게 익숙한 일정 관리 앱 중 하나로, 이를 프래그먼트를 활용하여 각각의 기능을 나누어 구현해보겠습니다.

1. ToDoListFragment: 할 일 목록 화면

먼저, ToDo 앱의 메인 화면인 ToDoListFragment를 만들어보겠습니다. 이 화면에서는 사용자가 추가한 할 일 목록이 보여집니다.

1-1. ToDoListFragment.kt

class ToDoListFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: ToDoListAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_todo_list, container, false)

        recyclerView = view.findViewById(R.id.recyclerView)
        adapter = ToDoListAdapter(requireActivity())
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(activity)
        adapter.notifyDataSetChanged()
        adapter.onToDoItemClickListener = object : ToDoListAdapter.OnToDoItemClickListener {
            override fun onToDoItemClick(view: View, position: Int) {
                val mActivity = activity as MainActivity
                mActivity.showToDoDetailFragment()
            }
        }

        // 할 일 목록 초기화
        initToDoList()

        return view
    }

    private fun initToDoList() {
        // ToDo 항목 초기화 및 어댑터에 추가
        val todo1 = ToDoItem("쇼핑 가기", false)
        val todo2 = ToDoItem("운동하기", true)
        val todo3 = ToDoItem("독서하기", false)

        adapter.addToDoItem(todo1)
        adapter.addToDoItem(todo2)
        adapter.addToDoItem(todo3)
    }

}

1-2. ToDoListAdapter.kt

class ToDoListAdapter(
    private val mContext: Context,
    ) : RecyclerView.Adapter<ToDoListAdapter.ToDoViewHolder>() {

    private val toDoList = mutableListOf<ToDoItem>()
    var onToDoItemClickListener: OnToDoItemClickListener? = null

    interface OnToDoItemClickListener {
        fun onToDoItemClick(view: View, position: Int)
    }


    fun addToDoItem(toDoItem: ToDoItem) {
        toDoList.add(toDoItem)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ToDoViewHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.item_todo, parent, false)
        return ToDoViewHolder(view)
    }

    override fun onBindViewHolder(holder: ToDoViewHolder, position: Int) {
        holder.todoTitle.text = toDoList[position].title
        holder.todoCheck.isChecked = toDoList[position].isCompleted

        if (onToDoItemClickListener != null) {
            holder.itemView.setOnClickListener { v ->
                onToDoItemClickListener?.onToDoItemClick(v,position)
            }
        }
    }

    override fun getItemCount(): Int {
        return toDoList.size
    }

    inner class ToDoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var todoTitle = itemView.findViewById<TextView>(R.id.todoTitle)
        var todoCheck = itemView.findViewById<CheckBox>(R.id.todoCheckBox)
    }


}

2. ToDoDetailFragment: 할 일 상세 화면

이제 ToDoListFragment에서 선택한 할 일의 상세 내용을 보여주는 ToDoDetailFragment를 만들어보겠습니다.

2-1. ToDoDetailFragment.kt

class ToDoDetailFragment : Fragment() {

    private lateinit var todoTitle: TextView
    private lateinit var todoDescription: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_todo_detail, container, false)

        todoTitle = view.findViewById(R.id.todoTitle)
        todoDescription = view.findViewById(R.id.todoDescription)

        // ToDo 상세 내용 초기화
        initToDoDetail()

        return view
    }

    private fun initToDoDetail() {
        // 선택한 ToDo 항목의 상세 내용 표시
        val selectedToDo = getSelectedToDo() // 선택한 ToDo 항목 가져오기 (가정)
        todoTitle.text = selectedToDo?.title
        todoDescription.text = "상세 내용이 없습니다." // ToDo에 대한 상세 내용을 여기서 설정
    }

    private fun getSelectedToDo(): ToDoItem? {
        // 선택한 ToDo 항목 가져오는 로직 추가 (가정)
        // ToDoListFragment에서 선택한 항목을 어떻게 전달할지 고민해보세요.
        return null
    }
}

3. 프래그먼트 간의 화면 전환

이제 ToDoListFragment와 ToDoDetailFragment 간에 화면을 전환하는 방법을 알아보겠습니다. MainActivity에서 이전에 사용한 방법과 유사하게 FragmentManager와 FragmentTransaction을 사용하여 전환합니다.

3-1. MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var todoListFragment: ToDoListFragment
    private lateinit var todoDetailFragment: ToDoDetailFragment
    private lateinit var fragmentManager: FragmentManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fragmentManager = supportFragmentManager
        todoListFragment = ToDoListFragment()
        todoDetailFragment = ToDoDetailFragment()

        showToDoListFragment()

    }


    private fun showToDoListFragment() {
        val transaction = fragmentManager.beginTransaction()
        transaction.replace(R.id.fragmentContainer, todoListFragment)
        transaction.commit()
    }

    fun showToDoDetailFragment() {
        val transaction = fragmentManager.beginTransaction()
        transaction.replace(R.id.fragmentContainer, todoDetailFragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }

}

4. 레이아웃 및 리소스

위 예제에서 사용된 레이아웃 파일 및 리소스 파일은 다음과 같습니다.

4-1. fragment_todo_list.xml

<!-- ToDoListFragment의 레이아웃 파일 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:clipToPadding="false" />
</RelativeLayout>

4-2. fragment_todo_detail.xml

<!-- ToDoDetailFragment의 레이아웃 파일 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/todoTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToDo 제목"
        android:textSize="24sp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"/>

    <TextView
        android:id="@+id/todoDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="상세 내용이 없습니다."
        android:layout_below="@id/todoTitle"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

4-3. item_todo.xml

<!-- ToDo 항목을 나타내는 RecyclerView의 아이템 레이아웃 파일 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp"
    android:background="?android:attr/selectableItemBackground">

    <CheckBox
        android:id="@+id/todoCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginEnd="16dp" />

    <TextView
        android:id="@+id/todoTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="18sp"
        android:textStyle="bold" />
</LinearLayout>

4-4. activity_main.xml

<?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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

마무리

이제 ToDo 앱의 화면을 프래그먼트를 활용하여 구성하는 방법을 자세히 알아보았습니다. ToDoListFragment에서는 할 일 목록을 보여주고, ToDoDetailFragment에서는 선택한 ToDo 항목의 상세 내용을 표시합니다. 또한, MainActivity에서는 프래그먼트 간의 화면 전환을 담당하고 있습니다.

프래그먼트를 활용하면 앱을 모듈화하여 유지보수성과 재사용성을 높일 수 있습니다. 다음에는 프래그먼트 간의 통신과 더 복잡한 UI 패턴에 대해 다뤄보겠습니다. 계속해서 흥미로운 Kotlin 코딩되세요! 🚀

728x90
반응형
LIST
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함