안드로이드/개발관련(Kotlin)

화면 분할 및 크기 조절 (Layout Split)

닉네임못짓는사람 2024. 5. 15. 09:30
반응형

화면을 둘로 나눠서 중앙의 divider를 움직여 크기를 조절

 

ActivityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/parent_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/top_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/red"
        app:layout_constraintBottom_toTopOf="@id/guide_line"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide_line"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <FrameLayout
        android:id="@+id/drag_view"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintBottom_toBottomOf="@id/guide_line"
        app:layout_constraintTop_toTopOf="@id/guide_line" />

    <FrameLayout
        android:id="@+id/bottom_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/blue"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/guide_line" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

MainActivity.kt

class MainActivity : AppCompatActivity() {
    companion object {
        private const val MAX_PERCENT = 0.9f
        private const val MIN_PERCENT = 0.1f
    }

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSplitLayout()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun setSplitLayout() = binding.run {
        dragView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_MOVE -> {
                    val percent = (event.rawY / parentLayout.height).coerceIn(MIN_PERCENT, MAX_PERCENT)
                    guideLine.setGuidelinePercent(percent)
                }
            }
            true
        }
    }
}

 

 

현재 터치한 위치의 rawY를 가지고 layout에서 어느 위치에 있는지 percnet를 구하여 guideline을 이동시킨다.

그러면 guideline을 따라서 layout의 크기와 drag_view의 위치가 이동된다.

 

 

반응형