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()
}
}
실행 결과
뷰의 사이즈(너비, 높이)가 변화하는 것을 확인할 수 있습니다
'안드로이드 코틀린' 카테고리의 다른 글
[Kotlin][Android] ML Kit으로 QR 코드 인식하고 링크 연결하기 (0) | 2025.03.05 |
---|---|
[Kotlin][Android] 뷰 가시성 변경하기 (0) | 2025.02.28 |
[Kotlin][Android] ZXing 라이브러리 사용하여 QR 코드 생성 및 Intent 로 공유하기 (2) | 2025.02.26 |
[Kotlin][Android] 복합 대입 연산자 활용하기 (0) | 2025.02.25 |
[Kotlin][Android] 문자열 템플릿 활용하기 (0) | 2025.02.14 |