이 예제에서는 Android EditText의 입력 유형(InputType)을 코드로 프로그래밍 방식으로 설정하는 방법을 알아봅니다.
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:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
android:padding="4dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:onClick="SetInputTypeNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="클릭하면 EditText 입력 유형이 숫자로 변경됩니다" />
</LinearLayout>레이아웃에는 하나의 EditText와 하나의 Button이 포함되어 있습니다. 버튼을 클릭하면 SetInputTypeNumber 메서드가 호출되어 EditText의 입력 유형이 숫자 전용으로 변경됩니다.
3단계 — MainActivity 작성
다음 코드를 src/MainActivity.java에 추가합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
}
public void SetInputTypeNumber(View view) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
}핵심은 setInputType() 메서드입니다. 이 메서드에 InputType.TYPE_CLASS_NUMBER를 전달하면 해당 EditText는 숫자만 입력할 수 있게 되며, 소프트 키패드도 자동으로 숫자 키패드로 전환됩니다.
4단계 — AndroidManifest.xml 확인
다음 코드를 androidManifest.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭합니다. 옵션 목록에서 자신의 모바일 기기를 선택하면, 앱이 기기에 설치되고 기본 화면이 표시됩니다.

버튼을 클릭한 후 EditText를 탭하면, 일반 텍스트 키보드 대신 숫자 키패드가 나타나는 것을 확인할 수 있습니다. 이처럼 setInputType()을 활용하면 XML 속성 수정 없이도 런타임에 동적으로 입력 유형을 제어할 수 있습니다.