티스토리 뷰
안녕하세요, 안드로이드 앱 개발을 즐기는 여러분! 오늘은 사용자의 입력을 받고, 그 입력에 따라 어떻게 앱이 동작하는지에 대해 알아보겠습니다. 사용자와의 상호작용은 안드로이드 앱을 만들 때 핵심적인 부분 중 하나이며, 사용자의 편의성을 높이는 데에 기여합니다.
1. EditText를 활용한 텍스트 입력
사용자의 텍스트 입력을 받기 위해 EditText를 사용합니다. XML 레이아웃에서 EditText를 정의하고, Kotlin 코드에서 해당 EditText에 접근하여 값을 읽거나 설정할 수 있습니다.
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your text"
android:inputType="text"/>
val editText = findViewById<EditText>(R.id.editText)
val userInput = editText.text.toString()
2. Button과 이벤트 처리
사용자의 액션에 응답하기 위해 Button을 사용하고, 해당 버튼에 클릭 이벤트를 처리하는 리스너를 등록합니다.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onButtonClick"/>
fun onButtonClick(view: View) {
// 버튼이 클릭되었을 때 수행할 로직
}
3. CheckBox와 ToggleButton
사용자의 선택 여부를 받기 위해 CheckBox나 ToggleButton을 사용할 수 있습니다.
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms and conditions"/>
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="On"
android:textOff="Off"/>
val checkBox = findViewById<CheckBox>(R.id.checkBox)
val isAgreed = checkBox.isChecked
val toggleButton = findViewById<ToggleButton>(R.id.toggleButton)
val isToggleOn = toggleButton.isChecked
4. RadioButton과 RadioGroup
여러 개의 옵션 중 하나를 선택할 때는 RadioButton과 RadioGroup을 사용합니다.
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>
</RadioGroup>
val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
val selectedOptionId = radioGroup.checkedRadioButtonId
val radioButton1 = findViewById<RadioButton>(R.id.radioButton1)
val isOption1Selected = radioButton1.isChecked
5. 키보드 이벤트 처리
EditText 등의 입력 필드에 키보드 이벤트를 처리하려면 setOnKeyListener 메서드를 사용합니다.
val editText = findViewById<EditText>(R.id.editText)
editText.setOnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
// 엔터 키가 눌렸을 때 수행할 로직
return@setOnKeyListener true
}
return@setOnKeyListener false
}
6. 통합 예제: 간단한 할일 목록 앱
이제 위에서 배운 내용들을 활용하여 간단한 할일 목록 앱을 만들어보겠습니다. 사용자는 EditText에 할일을 입력하고, Button을 클릭하여 목록에 추가할 수 있습니다.
<!-- activity_main.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/todoEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your todo"
android:inputType="text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="onAddButtonClick"/>
<ListView
android:id="@+id/todoListView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
// MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val todoList = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setupUI()
}
private fun setupUI() {
binding.addTodoButton.setOnClickListener { onAddButtonClick() }
val listView = findViewById<ListView>(R.id.todoListView)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, todoList)
listView.adapter = adapter
}
private fun onAddButtonClick() {
val todoEditText = findViewById<EditText>(R.id.todoEditText)
val newTodo = todoEditText.text.toString()
if (newTodo.isNotBlank()) {
todoList.add(newTodo)
updateTodoListView()
todoEditText.text.clear()
} else {
Toast.makeText(this, "Please enter a todo", Toast.LENGTH_SHORT).show()
}
}
private fun updateTodoListView() {
val listView = findViewById<ListView>(R.id.todoListView)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, todoList)
listView.adapter = adapter
}
}
마무리
이제 여러분은 안드로이드 앱에서 사용자의 입력을 받고, 다양한 이벤트를 처리하는 방법에 대해 알게 되었습니다. EditText, Button, CheckBox, RadioButton과 같은 다양한 UI 요소를 활용하여 사용자와의 상호작용을 더욱 풍부하게 만들 수 있습니다. 다음에는 화면 간 전환과 다양한 액티비티 생명주기에 대해 알아보도록 하겠습니다. 계속해서 흥미로운 Kotlin 코딩되세요! 🚀
'안드로이드 첫번째 걸음' 카테고리의 다른 글
Kotlin 기초 : 안드로이드 앱 개발을 위한 시작 (10. 프래그먼트(Fragment)와 그 사용법) (0) | 2023.12.28 |
---|---|
Kotlin 기초 : 안드로이드 앱 개발을 위한 시작 (9. 화면 간 전환과 다양한 액티비티 생명주기) (0) | 2023.12.27 |
Kotlin 기초 : 안드로이드 앱 개발을 위한 시작 (7. 데이터 저장 / 관리) (0) | 2023.12.25 |
Kotlin 기초 : 안드로이드 앱 개발을 위한 시작 (6. XML 레이아웃과 상호작용) (0) | 2023.12.22 |
Kotlin 기초 : 안드로이드 앱 개발을 위한 시작 (5. 널 안정성) (0) | 2023.12.22 |
- Total
- Today
- Yesterday
- kotlin
- 부동산
- fragment생명주기
- 안드로이드개발
- 클린아키텍처
- 앱개발
- 내부데이터베이스
- 경매
- 안드로이드앱개발
- Android
- MVVM패턴
- 생명주기
- RxJava
- 코루틴
- 안드로이드
- 코틀린
- Fragment
- 안드로이드 앱 개발
- cipher
- 부동산 경매
- 기초
- 디자인패턴
- 비동기
- 모듈화
- 안드로이드기초
- UI스레드
- RoomDatabase
- coroutine
- 비동기처리
- 사이버보안
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |