Thứ Năm, 29 tháng 3, 2018

Sử dụng EditText nhập dữ liệu trong lập trình Android

EditText

EditText (hoặc AppCompatEditText trong thư viện Support Design) là loại View hiện thị một hộp (chữ nhật) cho phép người dùng nhập dữ liệu (chữ, số ... có thể khống chế nhập liệu là text, số, phone, ngày tháng ...). Ví dụ màn hình dưới dùng EditText để người dùng nhập Tên, Ngày Sinh, Password ...
Nguồn: https://xuanthulab.net/su-dung-edittext-nhap-du-lieu-trong-lap-trinh-android.html


Do EditText mở rộng chức năng từ TextView, nến các tùy chọn thiết lập trình bày ở TextView vẫn đúng cho EditText như: màu chữ, font chữ, màu nền, hint, gán drawable vào các biên ... Nên các đặc tính đó không trình bày chi tiết, bạn nên đọc phần TextView trong Android trước để đảm bảo tính hệ thống của kiến thức.

Triển khai XML EditText

Tương tự TextView, mã XML EditText có dạng:
 <EditText
     android:id="@+id/textview"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:inputType="text"/>

Một số thiết lập

  • Thiết lập kiểu nhập liệu
    Thuộc tính android:inputType dùng để thiết lập kiểu nhập liệu, hiện thị. Tương ứng với mỗi kiểu này EditText sẽ có cách hiện thị cũng như liên kết với loại bàn phím tương ứng. Ví dụ như thiết lập nhập password thì dữ liệu nhập vào sẽ hiện thị bằng ký hiệu *, hay chọn dữ liệu số thì bàn phím xuất hiện là loại bàn phím số
    Các hằng số gán vào android:inputType có thể kết hợp nhiều loại với nhau bằng phép toán |, tham khảo đầy đủ tại: inputType, ở đây là một số giá trị hay dùng:
    Hằng XML Code Java và ý nghĩa
    date
    editText.setInputType(InputType.TYPE_CLASS_DATETIME
    | InputType.TYPE_DATETIME_VARIATION_DATE);
    Nhập ngày tháng
    datetime
    editText.setInputType(InputType.TYPE_CLASS_DATETIME |
    InputType.TYPE_DATETIME_VARIATION_NORMAL);
    Nhập ngày tháng, giờ
    number
    editText.setInputType(InputType.TYPE_CLASS_NUMBER | 
    InputType.TYPE_NUMBER_VARIATION_NORMAL.);
    Nhập số
    numberDecimal
    editText.setInputType(InputType.TYPE_CLASS_NUMBER |
    InputType.TYPE_NUMBER_FLAG_DECIMAL);
    Nhập số thập phân
    numberSigned
    TYPE_CLASS_NUMBER |
    InputType.TYPE_NUMBER_FLAG_SIGNED
    Nhập số nguyên không dấu
    phone
    editText.setInputType(InputType.TYPE_CLASS_PHONE);
    Nhập số diện thoại
    text
    editText.setInputType(InputType.TYPE_CLASS_TEXT |
    InputType.TYPE_TEXT_VARIATION_NORMAL);
    Nhập văn bản
    textEmailAddress
    editText.setInputType(InputType.TYPE_CLASS_TEXT |
    InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
    Địa chỉ Email
    textMultiLine
    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    Chữ trên nhiều dòng
    textPassword
    editText.setInputType(InputType.TYPE_CLASS_TEXT |
    InputType.TYPE_TEXT_VARIATION_PASSWORD);
    Nhập password
    textUri
    editText.setInputType( TYPE_CLASS_TEXT |
    InputType.TYPE_TEXT_VARIATION_URI);
    Địa chỉ URL
    time
    editText.setInputType(InputType.TYPE_CLASS_DATETIME |
    InputType.TYPE_DATETIME_VARIATION_TIME);
    Thời gian
    Giới hạn dòng chữ nhập trên một dòng
    <EditText
        android:maxLines="1"
        android:lines="1"
    />
    Giới hạn loại ký tự số nhập vào(chấp nhận số 0, 1)
    <EditText
      android:inputType="number"
      android:digits="01"
    />
    Chỉnh màu Hightlight
    <EditText
    android:textColorHighlight="#7cff88"
    />
  • Nhận thông tin khi đang nhập liệu
    Nếu muốn nhận giám sát, nhận ngay dữ liệu trong EditText khi người dùng đang nhập dữ liệu (có ích khi cần lưu lại ngay thông tin đang nhập) thì sử dụng phương thức addTextChangedListener với tham số là một đối tương TextWatcher, ví dụ:
    final EditText editText = findViewById(R.id.edittext);
    final TextView textView = findViewById(R.id.textviewid);
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence,
            int i, int i1, int i2) {
    
            //Gọi trước khi text thay đổi
        }
    
        @Override
        public void onTextChanged(CharSequence charSequence,
            int i, int i1, int i2) {
            //Gọi khi thay đổi
        }
    
        @Override
        public void afterTextChanged(Editable editable) {
            //Gọi sau khi thay đổi
            textView.setText(editText.getText().toString());
    
        }
    });
    Dữ liệu nhập vào EditText, mỗi khi thay đổi lập tức cập nhật vào TextView
  • Thiết lập icon Drawable và hint vào EditText
    Thực hiện giống hoàn toàn TextView hoặc Button, ví dụ có một icon: drawable/passwordicon thì bạn thực hành như sau:
    <EditText
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:textColorHint="#a30000"
        android:drawableLeft="@drawable/passwordicon"
        android:drawableTint="#3ca40f"
        android:drawablePadding="10dp"
        android:hint="Nhập password từ 6 ký tự trở lên"
        android:layout_height="wrap_content" />
    Bạn đã thêm dòng gợi ý và một icon ở bên trái (bạn có thể đặt ở bên phải, trên, dưới)
  • Tay đổi màu đường kẻ chân EditText
    Để làm điều này hãy thêm những phần tử sau vào Theme mà sử dụng cho Activity (mở file value/styles.xml):
    <item name="colorControlNormal">#000000</item>
    <item name="colorControlActivated">#28c99e</item>
    <item name="colorControlHighlight">#d94ed0</item>

TextInputLayout và TextInputEditText

Thư viện Support Design cung cấp một lớp TextInputEditText nó mở rộng từ chính EditText nên bạn có thể dùng nó giống hoàn toàn như EditText. Tuy nhiên TextInputEditText được thiết kế với mục đích chính là làm phần tử con của phần tử TextInputLayout, lúc đó TextInputLayout sẽ bao bọc lấy EditText và hiện thị các thông tin về EditText như: gợi ý (hint), đếm số ký tự, hiện thị thông báo lỗi ...
Để sử dụng cần đảm bảo tích hợp thư viện com.android.support:design vào Gradle
Triển khai XML TextInputLayout và TextInputEditText đi theo cặp dạng:
implementation 'com.android.support:design:27.1.0
 <android.support.design.widget.TextInputLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content">

     <android.support.design.widget.TextInputEditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:hint="@string/form_username"/>
 </android.support.design.widget.TextInputLayout>

Thiết lập TextInputLayout

Để hiện thị hint của TextInputEditText/Edit thiết lập: app:hintEnabled="true"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:padding="20px"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/usernameWrapper"
        android:layout_width="match_parent"
        app:hintEnabled="true"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:maxLength="10"
            android:hint="Nhập username"
          />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        app:hintEnabled="true"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="Nhập password" />

    </android.support.design.widget.TextInputLayout>
</LinearLayout>

Để hiện thí số ký tự nhập vào (hiện thị bên phải, dưới EditText) thiết lập: app:counterEnabled="true"

Để hiện thiết lập số ký tự lớn nhất, ví dụ 10 ký tự thêm vào app:counterMaxLength="10" đồng thời ở TextEdit (TextInputEditText) thiết lập android:maxLength="10"

Để hiện thị nút bấm vào để hiện thị nội dung password thay vì ký tự * trong EditText kiểu password, thì TextInputLayout cần có thuộc tính app:passwordToggleEnabled="true" (nếu muốn hiện thị nút riêng thay vì hình con mắt mặc định sử dụng app:passwordToggleDrawable để gán ảnh vào

Để hiện thị dòng thông báo lỗi, thiết lập app:errorEnabled="true" và dòng thông báo lỗi được thiết lập bằng code Java: setError()
Ví dụ, hiện thị dòng thông báo lỗi nếu username nhập vào rỗng
final TextInputEditText editText = findViewById(R.id.username);
final TextInputLayout usernameWrapper = findViewById(R.id.usernameWrapper);

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (charSequence.length() ==0) {
            usernameWrapper.setError("Bạn bắt buộc phải nhập usernam");
        } else {
            usernameWrapper.setError(null);
        }

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

AutoCompleteTextView

Cũng là một lớp mở rộng từ EditText, nhưng cho phép gợi ý, lựa chọn từ một danh sách đổ xuống để hoàn thành dữ liệu nhập vào. Dữ liệu, các View hiện thị gợi ý được thiết lập bằng một Adapter với phương thức setAdapter Ví dụ:
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:padding="20px"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:hint="Nhập sản phẩm?"
        android:id="@+id/product"
        android:completionThreshold="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.TextInputLayout>
</LinearLayout>
Code Java

public class MainActivity extends AppCompatActivity {

    //Mảng dữ liệu từ gợi ý (string)
    private static final String[] PRODUCTS = new String[]
    {
            "Điện thoại XY",
            "Máy tính AZ",
            "Iphone", "Tai nghe", "Loa"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        AutoCompleteTextView textView = findViewById(R.id.product);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, PRODUCTS);

        textView.setAdapter(adapter);

    }


}

Chú ý trong code trên android:completionThreshold="1" gõ một ký tự đã tiến hành gợi ý.

Nguồn: https://xuanthulab.net/su-dung-edittext-nhap-du-lieu-trong-lap-trinh-android.html

Không có nhận xét nào :

Đăng nhận xét

Danh mục Gửi liên hệ

Loading...