ภาพรวม
ตัวอย่างนี้สาธิตการเปลี่ยน Input Type ของ EditText แบบไดนามิกด้วยเมธอด setInputType()
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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="Click Here to set EditText input type to number" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (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);
}
}
Input Type ที่ใช้บ่อย
| Constant | คำอธิบาย |
|---|---|
TYPE_CLASS_TEXT | ข้อความทั่วไป |
TYPE_CLASS_NUMBER | ตัวเลขเท่านั้น |
TYPE_CLASS_PHONE | เบอร์โทรศัพท์ |
TYPE_TEXT_VARIATION_PASSWORD | รหัสผ่าน (ซ่อนตัวอักษร) |
TYPE_TEXT_VARIATION_EMAIL_ADDRESS | อีเมล |
TYPE_TEXT_FLAG_MULTI_LINE | หลายบรรทัด |
สามารถรวมได้ด้วย Bitwise OR: InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
ขั้นตอนที่ 4: 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>
การทดสอบ
รันแอป กดปุ่ม จะเห็นคีย์บอร์ดเปลี่ยนเป็นตัวเลขทันที
