BÀI 35 - AUTO COMPLETE TEXT TRONG LẬP TRÌNH ANDROID

Chức năng này hoạt động trên EditText. Chức năng auto complete này có thể thực hiện AutoCompleteTextViewMultiAutoCompleteTextView (như hình bên dưới á). Còn hình bên cạnh là cách hoạt động lần lượt của 2 dạng này (cái đầu là EditText thôi, 2 cái cuối là cái mình cần quan tâm).

2 dạng này là những đoạn code dạng xml bình thường thôi.

Giờ mình chuyển qua code java nhe!

// Đầu tiên, cũng khai báo các thứ cần dùng đến. Bla blaaa...

private EditText textFullname;

private AutoCompleteTextView textCountry;

private MultiAutoCompleteTextView textProgrammingLanguage;


// Sau đó, khai báo mảng chứa các từ hoàn thành khi người dùng mới bấm mấy ký tự đầu

private String[] countries = {"Vietnam","England","Canada", "France","Australia"};

private String[] languages = {"Java ","CSharp","Visual Basic","Swift","C/C++"};


// Tiếp đến là code trong hàm OnCreate, cái này trong bài về listView mình có bài hướng dẫn rồi á! Đơn giản chỉ cần tạo một cái arrayAdapter để liên kết với mảng thôi à.


ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,countries);

textCountry.setAdapter(adapter);

textCountry.setThreshold(1); // Cái này là set bao nhiêu ký tự thì bật lệnh nhắc


ArrayAdapter aLanguages = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);

textProgrammingLanguage.setAdapter(aLanguages);

textProgrammingLanguage.setThreshold(1);

// Đoạn code bên dưới cho phép người dùng nhập thêm nội dung, nội dung sau cách nội dung trước bằng dấu phẩy.

textProgrammingLanguage.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());



Vậy là xong rồi á!

Chuyển arrayList sang array để làm chức năng lưu và autoCompleteTextView

arrayListAutoText = new ArrayList<>();

arrayListAutoText .add("Đội");

arrayListAutoText .add("Team");

arrayListAutoText .add("Giám khảo");

arrayListAutoText .add("judgus");

arrayText = arrayListAutoText.toArray(new String[0]); //arrayList.toArray(new String[arrayList.size()]);

ArrayAdapter<String> adapter = new ArrayAdapter<>(this

, R.layout.support_simple_spinner_dropdown_item, arrayText);

editText.setAdapter(adapter);

editText.setThreshold(1);


button.setOnClickListener(v -> {

String Text = editText.getText().toString();

if (!Text.equals("")) {

arrayListAutoText.add(Text);

arrayText = arrayListAutoText.toArray(new String[0]);

adapter.notifyDataSetChanged();

}

});

editText.addTextChangedListener(new TextWatcher() {

@Override

public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

arrayText = arrayListAutoText.toArray(new String[0]);

ArrayAdapter<String> adapterAutoFind

= new ArrayAdapter<>(Activity.this

, R.layout.support_simple_spinner_dropdown_item, arrayAutoText);

editText.setAdapter(adapter);

editText.setThreshold(1);

}

@Override

public void afterTextChanged(Editable s) {

}

});