본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 뷰 사이즈 변경하기

by teamnova 2025. 3. 7.
728x90

오늘은 SeekBar를 활용해 뷰사이즈를 변경하는 예시를 만들어 보겠습니다

 

 

 

 

레이아웃 xml 파일 코드(activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- 크기를 변경할 타겟 뷰 -->
    <View
        android:id="@+id/target_view"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:background="@android:color/holo_blue_dark"
        app:layout_constraintBottom_toTopOf="@id/controls_layout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- 컨트롤 섹션 -->
    <LinearLayout
        android:id="@+id/controls_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <!-- 너비 조절 섹션 -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="너비 조절"
            android:textStyle="bold" />

        <SeekBar
            android:id="@+id/width_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp" />

        <TextView
            android:id="@+id/width_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:text="너비: 150dp" />

        <!-- 높이 조절 섹션 -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="높이 조절"
            android:textStyle="bold" />

        <SeekBar
            android:id="@+id/height_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp" />

        <TextView
            android:id="@+id/height_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:text="높이: 150dp" />

        <!-- 리셋 버튼 -->
        <Button
            android:id="@+id/reset_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="원래 크기로 복원" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

 

 

 

액티비티 코틀린 코드

class MainActivity : AppCompatActivity() {

    private lateinit var targetView: View
    private lateinit var widthSeekBar: SeekBar
    private lateinit var heightSeekBar: SeekBar
    private lateinit var widthValueText: TextView
    private lateinit var heightValueText: TextView
    private lateinit var resetButton: Button

    // 뷰의 원래 크기를 저장
    private var originalWidth = 0
    private var originalHeight = 0

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

        // 뷰 초기화
        targetView = findViewById(R.id.target_view)
        widthSeekBar = findViewById(R.id.width_seekbar)
        heightSeekBar = findViewById(R.id.height_seekbar)
        widthValueText = findViewById(R.id.width_value)
        heightValueText = findViewById(R.id.height_value)
        resetButton = findViewById(R.id.reset_button)

        // 초기 값을 설정하기 위해 레이아웃이 그려진 후 실행
        targetView.post {
            originalWidth = targetView.width
            originalHeight = targetView.height

            // SeekBar 초기화
            widthSeekBar.max = 500
            heightSeekBar.max = 500
            widthSeekBar.progress = 0
            heightSeekBar.progress = 0

            updateSizeText(originalWidth, originalHeight)
        }

        // 너비 변경 리스너
        widthSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val newWidth = originalWidth + dpToPx(progress)
                changeViewWidth(newWidth)
                updateSizeText(newWidth, targetView.height)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 높이 변경 리스너
        heightSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val newHeight = originalHeight + dpToPx(progress)
                changeViewHeight(newHeight)
                updateSizeText(targetView.width, newHeight)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 리셋 버튼 리스너
        resetButton.setOnClickListener {
            widthSeekBar.progress = 0
            heightSeekBar.progress = 0
            changeViewSize(originalWidth, originalHeight)
            updateSizeText(originalWidth, originalHeight)
        }
    }

    // 뷰 너비 변경 함수
    private fun changeViewWidth(width: Int) {
        val params = targetView.layoutParams
        params.width = width
        targetView.layoutParams = params
    }

    // 뷰 높이 변경 함수
    private fun changeViewHeight(height: Int) {
        val params = targetView.layoutParams
        params.height = height
        targetView.layoutParams = params
    }

    // 뷰 사이즈 변경 함수 (너비와 높이 모두)
    private fun changeViewSize(width: Int, height: Int) {
        val params = targetView.layoutParams
        params.width = width
        params.height = height
        targetView.layoutParams = params
    }

    // 뷰 사이즈 텍스트 업데이트
    private fun updateSizeText(width: Int, height: Int) {
        widthValueText.text = "너비: ${width}px (${pxToDp(width)}dp)"
        heightValueText.text = "높이: ${height}px (${pxToDp(height)}dp)"
    }

    // dp를 px로 변환
    private fun dpToPx(dp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp.toFloat(),
            resources.displayMetrics
        ).toInt()
    }

    // px를 dp로 변환
    private fun pxToDp(px: Int): Int {
        return (px / resources.displayMetrics.density).toInt()
    }
}

 

 

실행 결과

 

뷰의 사이즈(너비, 높이)가 변화하는 것을 확인할 수 있습니다