Nếu bạn chú ý vào khung nhập URL của trình Web,bạn sẽ thấy khi ta đang nhập tứng kí tự nếu phù hợp với lịch sử trình duyệt nó sẽ hiện ra những đia chỉ mà ta từng truy cập đây là một ứng dụng cụ thể của việc bắt sự kiện text thay đổi trong EditText.
Nào bây giờ chúng ta vào bài ngày hôm nay!
Bắt sự kiện trong EditText
Tôi có tạo một ví dụ với giao diện đơn giản như sau:
Tôi giải thích sơ qua:Khi đang trong quá trình nhập dữ liệu nó sẽ tự động tính toán và đưa kết quả mà ta không cần phải nhấn một nút nào cả.
-Tạo một Project có tên EditText:
-Trong file activity_main.xml ta nhập:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#ffff00"
android:background="#0000ff"
android:text="Trình tính tổng 2 số:" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_alignParentRight="true"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/textView2"
android:ems="10"
android:hint="Nhập số thứ hai!(6 text)"
android:inputType="numberDecimal"
android:textSize="16sp"
android:gravity="center"
android:maxLength="6" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText2"
android:layout_marginTop="34dp"
android:background="#0000ff"
android:padding="10dp"
android:text="Kết Quả:"
android:textColor="#ff0000"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:background="#fff000"
android:padding="10dp"
android:text="Số a:"
android:textColor="#ff0000" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true"
android:ems="10"
android:gravity="center"
android:hint="Nhập số thứ nhât!(4 text)"
android:inputType="numberDecimal"
android:textSize="16sp"
android:maxLength="4" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="22dp"
android:layout_toLeftOf="@+id/editText2"
android:background="#fff000"
android:padding="10dp"
android:text="Số b:"
android:textColor="#ff0000" />
</RelativeLayout>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#ffff00"
android:background="#0000ff"
android:text="Trình tính tổng 2 số:" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_alignParentRight="true"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/textView2"
android:ems="10"
android:hint="Nhập số thứ hai!(6 text)"
android:inputType="numberDecimal"
android:textSize="16sp"
android:gravity="center"
android:maxLength="6" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText2"
android:layout_marginTop="34dp"
android:background="#0000ff"
android:padding="10dp"
android:text="Kết Quả:"
android:textColor="#ff0000"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:background="#fff000"
android:padding="10dp"
android:text="Số a:"
android:textColor="#ff0000" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true"
android:ems="10"
android:gravity="center"
android:hint="Nhập số thứ nhât!(4 text)"
android:inputType="numberDecimal"
android:textSize="16sp"
android:maxLength="4" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="22dp"
android:layout_toLeftOf="@+id/editText2"
android:background="#fff000"
android:padding="10dp"
android:text="Số b:"
android:textColor="#ff0000" />
</RelativeLayout>
Ở đây gravity thiết lập vị trí của text nhập vào:trung tâm,bên trái,bên phải...
inputType.:quy định kiểu dữ liệu được nhập vào.Trong trường hợp này là số.
-class MainActivity có nội dung như sau:
package com.example.edittext;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText a,b;
private TextView KQ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KQ=(TextView)
findViewById(R.id.textView5);
a=(EditText)
findViewById(R.id.editText1);
b=(EditText)
findViewById(R.id.editText2);
//Bắt sự kiện thay đổi số b
a.addTextChangedListener(new TextWatcher() {
//Đang thay đổi
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if(b.getText().toString().equals("")==false){ //Kiểm tra nếu edittext 2 khống trống thì tính nếu trống thì thôi
//nếu ko check sẽ gây lỗi khi edittext 2 trống
//ép kiểu về String
String text=arg0.toString();
double so_a=Double.parseDouble(text); //java căn bản tôi ko giải thích
String text_b=b.getText().toString(); //lấy text trong edittext 2
double so_b=Double.parseDouble(text_b);
//thực hiện tính và đưa ra kết quả
double ketqua=so_a+so_b;
KQ.setText(ketqua+"");
}
else{
KQ.setText("0.0");
}
}
//Trước khi thay đổi
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
//Sau khi thay đổi
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
//Bắt sự kiện thay đổi số b
b.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if(a.getText().toString().equals("")==false){
String text_a=a.getText().toString();
double so_a=Double.parseDouble(text_a);
String text=arg0.toString();
double so_b=Double.parseDouble(text);
//thực hiện tính và đưa ra kết quả
double ketqua=so_a+so_b;
KQ.setText(ketqua+"");
}
else{
KQ.setText("0.0");
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
-cuối cùng là chạy thử xem và kết quảimport android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText a,b;
private TextView KQ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KQ=(TextView)
findViewById(R.id.textView5);
a=(EditText)
findViewById(R.id.editText1);
b=(EditText)
findViewById(R.id.editText2);
//Bắt sự kiện thay đổi số b
a.addTextChangedListener(new TextWatcher() {
//Đang thay đổi
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if(b.getText().toString().equals("")==false){ //Kiểm tra nếu edittext 2 khống trống thì tính nếu trống thì thôi
//nếu ko check sẽ gây lỗi khi edittext 2 trống
//ép kiểu về String
String text=arg0.toString();
double so_a=Double.parseDouble(text); //java căn bản tôi ko giải thích
String text_b=b.getText().toString(); //lấy text trong edittext 2
double so_b=Double.parseDouble(text_b);
//thực hiện tính và đưa ra kết quả
double ketqua=so_a+so_b;
KQ.setText(ketqua+"");
}
else{
KQ.setText("0.0");
}
}
//Trước khi thay đổi
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
//Sau khi thay đổi
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
//Bắt sự kiện thay đổi số b
b.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if(a.getText().toString().equals("")==false){
String text_a=a.getText().toString();
double so_a=Double.parseDouble(text_a);
String text=arg0.toString();
double so_b=Double.parseDouble(text);
//thực hiện tính và đưa ra kết quả
double ketqua=so_a+so_b;
KQ.setText(ketqua+"");
}
else{
KQ.setText("0.0");
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Chỉ định các hành động của bàn phím
Trước tiên chúng ta xem một số hình ảnh bàn phím và EditText và xem chúng khác nhau ở đâu:
-EditText thông thường:

-EditText của Web Brower:
-EditText của google search:

Như chúng ta thấy chúng khác nhau ở chỗ phím carriage return.Đối với EditText thông thường đơn giản nó chỉ là phím xuống dòng nhưng ở Web brower và google search thì nó lại là 2 action "Đến" và "Tìm Kiếm".
Tại sao lại cần làm vậy? Bởi đơn giản nó tiện cho user hơn.
-Để chỉ định action cho EditText ta sử dụng thuộc tinh android:imeOptions:
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:imeOptions="actionSearch" <!-- Action tìm kiếm -->
android:ems="10" />
Ngoài
actionSearch chúng ta còn rất nhiều action khác
như:actionSend,actionGo,actionNext...Mặc định khi có từ 2 EditText trở
lên nó sẽ là actionNext,để loại bỏ action mặc định chúng ta có thể sử dụng actionNonrandroid:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:imeOptions="actionSearch" <!-- Action tìm kiếm -->
android:ems="10" />
Phản hồi lại action của sự kiến nút ấn
Nếu bạn chỉ định một action bàn phím cho phương thức đầu vào sử dụng attribute android:imeOptions (chẳng hạn “actionSend”), bạn có thể lắng nghe sự kiện hành động cụ thể sử dụng một TextView.OnEditorActionListener. Interface TextView.OnEditorActionListener cung cấp một hàm hồi quy gọi hàm onEditorAction() cho biết loại hành động nào được triệu gọi với một action ID chẳng hạn IME_ACTION_SEND hoặc IME_ACTION_SEARCH.
EditText editText = (EditText) findViewById(R.id.search); editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { // Send the user message handled = true; } return handled; } });
Tôi xin tạm dừng vấn đề về EditText ở đây!
Bài tập dành cho các bạn trong phần này:
-Tạo một app như sau:

+Thiết lập actionSearch cho EditText (1),actionSend cho EditText (2) như tôi đã đánh dấu trên ảnh
+Khi nhấn action của EditText (1) thì thực hiện phép "+", action của EditText (2) thì thực hiện phép "x".Và xuất kêt quả lên TextView.
Download source code:EditText
Mọi thắc mắc,góp ý xin vui lòng comment tại fan page:android
làm thế nào khi thay đổi giá trị tiếp theo trong ô edittext nó vẫn trả về kết quả thay vì out khỏi app vậy ạ
ReplyDeleteBạn xét điều kiện cho biến arg0 là được, nếu nó rỗng thì không thực hiện gì, còn nó chứa giá trị thì mới thực hiện những câu lệnh tiếp theo.
Deletebạn có thể cho hướng dẫn ko bạn?
ReplyDelete