728x90
반응형
1. 새 프로젝트 생성
- Name: cat
- Package name: com.mybea1109.cat
- Language: Java
- Minimum SDK: API 24 (Nougat, Android 7.0)
- 빌드 언어: Kotlin DSL (권장값)
새로운 Empty Activity로 프로젝트를 시작합니다.
2. 앱 UI 구성하기 (activity_main.xml)
🔸 핵심 UI 구성요소
요소 설명
ImageView | 귀여운 고양이 사진을 표시합니다. |
EditText | 고양이의 출생 연도를 입력받습니다. |
Button | 생일 계산하기 기능을 실행합니다. |
TextView | 계산된 고양이의 나이를 출력합니다. |
1)ImageView 설정하기
<ImageView
android:id="@+id/imageView2"
android:layout_width="0dp"
android:layout_height="238dp"
android:layout_marginStart="16dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="16dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/cat_2" />
- ImageView 추가 방법
Palette의 ImageView를 화면으로 드래그합니다. - 이미지 리소스 설정
오른쪽 속성 창에서 srcCompat 속성에 @drawable/cat_2를 입력해 고양이 이미지를 적용합니다. - 크기 및 배치
- layout_width="0dp" (부모 기준 가득 채움)
- layout_height="238dp"
- scaleType="centerCrop"으로 설정해 이미지가 중심을 기준으로 잘리면서 꽉 차게 표시됩니다.
- 제약 조건(Constraint)
화면의 맨 위에 배치되도록 Top, Start, End를 parent에 연결합니다.
2) EditText 추가 및 설정
<EditText
android:id="@+id/editYear"
android:layout_width="230dp"
android:layout_height="60dp"
android:layout_marginStart="55dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="55dp"
android:ems="10"
android:inputType="text"
android:text="고양이 이름을 입력하세요."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
- 추가 방법
Palette의 Text → Plain Text 항목을 드래그하여 배치합니다. - 텍스트 힌트 설정
text="고양이 이름을 입력하세요."
사용자에게 입력을 유도하는 문구를 기본 텍스트로 제공합니다. - 배치 제약 조건
- Top → ImageView의 Bottom
- Start, End → parent
- 권장 설정
- layout_width="230dp"
- layout_height="60dp"
- inputType="text"
- 마진을 통해 적절한 공간 확보 (layout_marginTop="40dp")
3) Button 추가 및 정렬
<Button
android:id="@+id/btnAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="42dp"
android:layout_marginEnd="20dp"
android:text="생일 계산하기"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editYear" />
- 버튼 텍스트 설정
text="생일 계산하기" - 배치 제약 조건
- Top → EditText의 Bottom
- Start, End → parent
- 위치 조정
- layout_marginTop="42dp"
- 버튼을 중앙 하단에 넉넉하게 정렬
- 기본 폭 설정
layout_width="match_parent"로 전체 너비를 채움 - 추가 옵션
Horizontal Bias로 좌우 정렬 미세 조정 가능
4) TextView로 결과 출력
<TextView
android:id="@+id/tetAge"
android:layout_width="243dp"
android:layout_height="62dp"
android:layout_marginStart="55dp"
android:layout_marginTop="55dp"
android:layout_marginEnd="55dp"
android:text="나이"
android:textAlignment="center"
android:textColor="#090909"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnAge" />
구성 포인트
- ConstraintLayout을 사용하여 모든 요소를 깔끔하게 중앙 정렬
- ImageView는 centerCrop으로 고양이 사진 비율 유지
- EditText는 힌트 문구 설정 (고양이 이름을 입력하세요)
- Button은 적절한 마진과 비율로 사용자 친화적 배치
- TextView는 결과 표시를 위한 중앙 정렬 설정
3. 기능 구현 (MainActivity.java)
기능 설명
- 사용자가 출생 연도를 입력 → 현재 연도와의 차이를 계산 → 나이를 화면에 출력
- 나이가 0세 미만 또는 20세 초과일 경우 경고 메시지를 띄움
private void calculateAge() {
String strYear = editYear.getText().toString().trim();
if (strYear.isEmpty()) {
Toast.makeText(MainActivity.this, "나이를 입력하세요", Toast.LENGTH_SHORT).show();
return;
}
try {
int year = Integer.parseInt(strYear);
int now = Calendar.getInstance().get(Calendar.YEAR);
int age = now - year;
if (age < MIN_AGE || age > MAX_AGE) {
Toast.makeText(MainActivity.this,
String.format("나이는 %d세에서 %d세 사이여야 합니다", MIN_AGE, MAX_AGE),
Toast.LENGTH_SHORT).show();
editYear.setText("");
return;
}
txtAge.setText("나이 : " + age + "살입니다.");
Log.i("MainActivity", "계산된 나이: " + age);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "올바른 숫자를 입력하세요", Toast.LENGTH_SHORT).show();
}
}
주요 변수 설정
private EditText editYear;
private Button btnAge;
private TextView txtAge;
private static final int MIN_AGE = 0;
private static final int MAX_AGE = 20;
4. 사용자 인터랙션 흐름
- 앱을 실행 → 고양이 이미지가 상단에 표시됨
- 사용자 → 출생 연도 입력 (예: 2015)
- [생일 계산하기] 버튼 클릭
- TextView에 "나이: 9살입니다." 같은 결과가 출력됨
5. 전체 코드 정리
activity_main.xml
UI는 앞서 설명한 구성대로 정의합니다.
MainActivity.java
- onCreate(): UI 요소 연결
- calculateAge(): 입력값 검증 및 나이 계산 로직
마무리
이 프로젝트는 초보자도 쉽게 따라할 수 있는 간단한 입력 → 계산 → 출력 흐름의 로직 예제입니다.
고양이 나이를 예로 들었지만, 반려동물 관리 앱, 나이 기반 건강 지표 계산 등 다양한 확장도 가능합니다.
728x90
반응형
'Frontend > 실습' 카테고리의 다른 글
167. [AI][Android Studio] 로직개발하기 : 다중페이지 개발(Activity Lifecycle) (0) | 2025.03.05 |
---|---|
166. [AI][Android Studio] 로직개발하기 : 타이머 앱 실습 (0) | 2025.03.04 |
164. [AI][Android Studio] 로직개발하기 : 주사위게임 앱 제작 (1) | 2025.03.03 |
163. [AI][Android Studio] Android Activity Lifecycle(활동 수명 주기) 완벽 가이드 (0) | 2025.03.03 |
162. [AI][Android Studio] 안드로이드 스튜디오 설치하는 방법 (0) | 2025.03.03 |