Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 EditText 입력값이 알파벳으로 시작하는지 확인하는 방법

이 튜토리얼에서는 Android에서 EditText(편집 텍스트)에 입력된 값의 첫 글자가 알파벳으로 시작하는지 여부를 확인하는 방법을 단계별로 알아봅니다.

구현 단계

1단계: 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 세부 정보를 모두 입력합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:orientation="vertical">
   <EditText
      android:id="@+id/edit_query"
      android:layout_width="match_parent"
      android:hint="Enter something"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/buttonPanel"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</LinearLayout>

위 레이아웃에는 EditText와 버튼 뷰가 포함되어 있습니다. 버튼을 클릭하면 EditText에 입력된 데이터가 알파벳으로 시작하는지 검증하도록 구성했습니다.

3단계: MainActivity 코드 작성

java/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final EditText edit_query = findViewById(R.id.edit_query);
      findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String data = edit_query.getText().toString();
            if (!data.isEmpty()) {
               char c = data.charAt(0);
               if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
                  Toast.makeText(MainActivity.this, c + " is an alphabet", Toast.LENGTH_LONG).show();
               else
                  Toast.makeText(MainActivity.this, c + " is not an alphabet.", Toast.LENGTH_LONG).show();
            }
         }
      });
   }
}

핵심 로직 살펴보기

  • 버튼을 클릭하면 EditText에 입력된 값을 문자열로 가져옵니다.
  • 먼저 isEmpty()로 입력값이 비어 있는지 확인해 오류를 방지합니다.
  • charAt(0)으로 첫 번째 문자를 추출한 뒤, 해당 문자가 소문자(a~z) 또는 대문자(A~Z) 범위에 속하는지 비교합니다.
  • 판별 결과에 따라 Toast 메시지로 알파벳 여부를 사용자에게 알려줍니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 Run 아이콘을 클릭하고, 기기 선택 목록에서 자신의 모바일 기기를 선택합니다. 그러면 모바일 화면에 아래와 같은 기본 화면이 표시됩니다.

Android에서 EditText 입력값이 알파벳으로 시작하는지 확인하는 방법