전체 코드 : https://github.com/ryr0121/AndroidPractice/tree/main/countingApp
구현결과
주요 기능
- 화면 상단에 카운팅된 숫자 표시
- '초기화' 버튼으로 숫자를 0으로 변경
- '+' 버튼으로 숫자를 1씩 증가
xml을 통해 UI 구현을 진행했고, LinearLayout을 통해 view를 배치함
LinearLayout은 배치 방향(orientation)의 값에 따라 세로 방향(vertical) 혹은 가로 방향(horizontal)으로 view 배치가 이루어짐
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
...
</LinearLayout>
포함시킨 view는 TextView와 Button임
여러 디바이스에서 동등한 크기로 표시하기 위해 고안된 단위인 "밀도 독립적 픽셀(DP)" 사용
(픽셀 단위를 사용할 경우 디바이스 별로 전체 픽셀이 다르기 때문에 같은 값이 서로 다른 크기로 표현될 수 있기 때문)
id값 지정을 통해 이후 activity에서 버튼 이벤트 발생 시 변경된 숫자값을 표시하는 것이 가능해짐
<TextView
android:id="@+id/numberTextView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:text="0"
android:textSize="100sp"
android:textColor="@color/blue"
android:textStyle="bold|italic"
android:gravity="center"
/>
'초기화' 버튼과 '+' 버튼을 수평 방향으로 나란히 배치하기 위해 orientation이 horizontal인 LinearLayout을 사용함
id값 지정을 통해 이후 activity에서 사용자의 버튼 클릭 이벤트 처리가 가능해짐
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/resetButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="초기화"
android:layout_weight="1"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:layout_marginStart="16dp"
/>
<Button
android:id="@+id/plusButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="+"
android:layout_weight="1"
android:layout_margin="16dp"
/>
</LinearLayout>
MainActivity 내에서 카운팅 현황을 나타내는 number 변수 선언 및 활용
findViewById 메소드를 활용하여 지정된 id의 view를 찾아와 활용
button의 setOnClickListener를 람다로 정의하여 사용자가 버튼 클릭 시 일어날 내용을 작성 (숫자를 0 혹은 +1 하여 변경)
class MainActivity : AppCompatActivity() {
private var number = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val numberTextView = findViewById<TextView>(R.id.numberTextView)
val resetButton = findViewById<Button>(R.id.resetButton)
val plusButton = findViewById<Button>(R.id.plusButton)
resetButton.setOnClickListener {
number = 0
numberTextView.text = number.toString()
}
plusButton.setOnClickListener {
number += 1
numberTextView.text = number.toString()
}
}
}
아요랑 다른데 비슷해,,,비슷한데 다른 늒김,,,,,암튼 첫 구현 도전 성공,,
'Android' 카테고리의 다른 글
[Android] "스톱워치 앱" 구현 (0) | 2024.07.02 |
---|---|
[Android] "계산기 앱" 구현 (0) | 2024.06.30 |
[Android] "응급 의료정보 앱" 구현 (0) | 2024.06.30 |
[Android] "단위 변환기 앱" 구현 (4) | 2024.06.26 |