Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตั้งค่า Input Type ให้ EditText โดยโปรแกรมใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการตั้งค่า InputType ให้ EditText โดยโปรแกรม (Programmatically) ใน Android โดยใช้ Kotlin

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_centerInParent="true"
        android:onClick="setInputTypeNumber"
        android:text="Click here" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.widget.EditText

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        editText = findViewById(R.id.editText)
    }

    fun setInputTypeNumber(view: View) {
        editText.inputType = InputType.TYPE_CLASS_NUMBER
    }
}

ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml

ใช้การตั้งค่ามาตรฐาน

ทดสอบการทำงาน

รันแอป กดปุ่ม "Click here" EditText จะเปลี่ยนเป็นคีย์บอร์ดตัวเลข

InputType ที่ใช้บ่อย

Constantคำอธิบาย
TYPE_CLASS_TEXTข้อความทั่วไป (Default)
TYPE_CLASS_NUMBERตัวเลขเท่านั้น
TYPE_CLASS_PHONEเบอร์โทรศัพท์
TYPE_TEXT_VARIATION_PASSWORDรหัสผ่าน (ซ่อนตัวอักษร)
TYPE_TEXT_VARIATION_EMAIL_ADDRESSอีเมล (มี @, .)
TYPE_TEXT_VARIATION_URIURL
TYPE_TEXT_FLAG_MULTI_LINEหลายบรรทัด
TYPE_TEXT_FLAG_CAP_WORDSตัวแรกของแต่ละคำใหญ่

รวม Flags ได้: editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE