EditText trong Android
Trong lập trình ứng dụng một widget không thể thiếu đó là Text box, trong android gọi là EditText. EditText sử dụng cho phép người dùng nhập thông tin để ứng dụng xử lý dưới dạng các text box.
Control này kế thừa từ TextView và cho phép chỉnh sửa dữ liệu (dĩ nhiên chúng ta có thể cấm chỉnh sửa dữ liệu bằng coding hay trong xml). Để sử dụng EditText rất đơn giản, chúng ta chỉ việc kéo thả control này vào giao diện và tiến
Các Text Fields trong Eclipse IDE cơ bản là EditText
Chúng ta có thể tạo một EditText trong tập tin XML hoặc khởi tạo EditText trong code Java
Code EditText trong XML
<EditText android:id="@+id/edtFirstName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="116dp" android:text="Nhập tên của bạn" android:ems="10" />
Truy xuất / Lấy giá trị từ EditText Trong Java Class:Dưới đây là mã ví dụ của EditText trong đó chúng tôi lấy ra giá trị từ một EditText trong lớp Java. Chúng tôi đã sử dụng mã này trong ví dụ bạn sẽ tìm thấy ở cuối bài đăng này.
EditText txtFirstName= (EditText) findViewById(R.id.edtFirstName); String editTextValue = txtFirstName.getText().toString();
Thuộc tính thường dùng của EditText
Bây giờ chúng xem một số thuộc tính hay sử dụng trong EditText trong tập tin XML
1. android:id: Là thuộc tính duy nhất của EditText. Xem ví dụ sau:
<EditText android:id="@+id/simpleEditText" android:layout_height="wrap_content" android:layout_width="match_parent"/>
Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:
EditText simpleEditText = (EditText) findViewById(R.id.simpleEditText); String editTextValue = simpleEditText.getText().toString();
2. android:gravity: Thuộc tính này thường sử dụng để canh nội dung trên EditText: left, right, center, top, bottom, center_vertical, center_horizontal
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter Email" android:gravity="right"/><!--gravity of a edit text-->
3. android:text: Thuộc tính này dùng xuất chuỗi văn bản lên EditText, Chúng ta có thể khai báo trong XML hoặc code Java.
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Username"/><!--set text in edit text-->
Gán nội dung cho EditText trong Java class:
EditText editText = (EditText)findViewById(R.id.simpleEditText); editText.setText("Username");//set the text in edit text
4. android:hint: Thuộc tính hint để hiển thị thông tin gợi ý trong vùng nhập dữ liệu khi bạn chưa nhập bất kỳ dữ liệu nào vào, chỉ cần có dữ liệu là phần hint sẽ tự động mất đi.
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="Enter Your Name Here" /><!--display the hint-->
Gán hint cho EditText trong Java class:
EditText editText = (EditText)findViewById(R.id.simpleEditText); editText.setHint("Enter Your Name Here");//display the hint
5. android:textColor: Thuộc tính này dùng xác định màu chữ, dạng màu chữ: “#argb”, “#rgb”, “#rrggbb”, hoặc “#aarrggbb”. Vi dụ sau set chữ trong EditText màu đỏ.
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Password" android:textColor="#f00"/><!--set the red text color-->
Set thuộc tính textColor cho EditText trong Java class:
EditText simpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setTextColor(Color.RED);//set the red text color
6. android:textColorHint: là thuộc tính set màu cho hint.
EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="Enter Your Name Here" android:textColorHint="#0f0"/><!--set the hint color green-->
Set thuộc tính textColorHint cho EditText trong Java class:
EditText simpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setHintTextColor(Color.green(0));//set the green hint color
7. android:textSize: Thuộc tính textSize xác định kích thước văn bản của EditText. Chúng ta có thể đ8ạ kích thước văn bản theo sp(scale independent pixel) hoặc dp(density pixel). Trong ví dụ này chúng ta xác định kich thước cho văn bản là 40sp.
Set thuộc tính textSize cho EditText trong Java class:
EditText simpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setTextSize(25);//set size of text
7. android:textStyle: Thuộc tính xác định loại văn bản của EditText, thông thường có các loại văn bản:bold, italic và normal. Nếu chúng ta muốn sử nhiều hơn một loại văn bản thì phải thêm phép toán hoặc "|" vào giữa các loại văn bản:
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Email" android:textSize="25sp" android:textStyle="bold|italic"/><!--set bold and italic text style-->
8. android:background: Thuộc tính này xác định màu nền cho EditText.
9. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của EditText với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=10sp từ mọi phía của EditText
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:hint="Enter Your Name Here" android:padding="15dp" android:textColorHint="#fff" android:textStyle="bold|italic" android:background="#000"/><!--set background color black-->
Set thuộc tính Background cho EditText trong Java class:
EditText simpleEditText=(EditText)findViewById(R.id.simpleEditText); simpleEditText.setBackgroundColor(Color.BLACK);//set black background color
10. android:inputType: Định dạng kiểu văn bản khi người dùng nhập vào(kiểu mật khẩu, kiểu số, kiểu email, phone, …).Trong ví dụ sau EditText chỉ được nhập số. Chúng ta thêm thuộc tính android:inputType="number"
11. android:maxLines: Cho phép người dùng nhập tối đa bao nhiêu dòng.
<EditText android:id="@+id/simpleEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="17dp" android:ems="10" android:maxLines="1" android:inputType="number" android:padding="15dp" > </EditText>
Ví dụ: Trong ví dụ này chúng ta sẽ lấy giá trị từ các EditText, sau đó hiển thị các giá trị này lên TextView thông qua một button được lập trình xử lý sự kiện trong Java Class (Button chúng ta sẽ tìm hiểu ở trang tiếp theo). Tiến hành tạo project, vào thư mục res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là TextView: File->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml , trong xml này chúng ta thêm nhiều TextView và EditText và một Button có sự kiện onClick trong Table Layout.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/TableLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="hiepsiit.com.edittext.MainActivity" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txtusername" /> <EditText android:id="@+id/editName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/txtPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txtpassword" /> <EditText android:id="@+id/edtPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" > <requestFocus /> </EditText> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/txtBirthday" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txtbirthday" /> <EditText android:id="@+id/edtBirthday" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="date" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/txtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/txtemail" /> <EditText android:id="@+id/edtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" /> </TableRow> <Button android:id="@+id/btnReg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btnreg" /> <TextView android:id="@+id/txtShowMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.21" android:inputType="textMultiLine" android:textAppearance="?android:attr/textAppearanceLarge" /> </TableLayout>
Chuyển quan XML đổi tên các điều khiển:
Điều khiển | android:id | android:text |
---|---|---|
TextView1 | txtName | @string/txtusername |
TextView2 | txtPassword | @string/txtpassword |
TextView3 | txtBirthday | @string/txtbirthday |
TextView4 | txtEmail | @string/txtEmail |
TextView5 | txtShowMessage | |
EditText1 | editName | |
EditText2 | edtPassword | |
EditText3 | edtBirthday | |
EditText4 | edtEmail | |
Button1 | btnReg | @string/btnReg |
Vào thư mục res/values bổ sung string.xml (Chúng ta không khai báo trực tiếp nhãn vào các điều khiển, mà thông qua string.xml)
<string name="app_name">EditText</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="txtusername">Tài khoản</string> <string name="txtpassword">Mật khẩu</string> <string name="txtemail">Email</string> <string name="txtbirthday">Ngày sinh</string> <string name="btnreg">Đăng ký</string>
Bước 3: Mở app -> src ->MainActivity.java và thêm code. Khi click vào Button sẽ lấy các giá trị của EditText, sau đó hiển thị lên TextView.
package hiepsiit.com.edittext; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { //Khai báo các widget private Button btnReg; private TextView txtShowMessage; private EditText edtName, edtPassword, edtBirthday, edtEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtName = (EditText)findViewById(R.id.edtName); edtPassword = (EditText)findViewById(R.id.edtPassword); edtBirthday = (EditText)findViewById(R.id.edtBirthday); edtEmail = (EditText)findViewById(R.id.edtEmail); txtShowMessage= (TextView)findViewById(R.id.txtShowMessage); btnReg = (Button)findViewById(R.id.btnReg); btnReg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String str="Thông tin tài khoản \n"; str+="Tài Khoản:"+edtName.getText().toString()+"\n Mật khẩu:"+edtPassword.getText().toString(); str+="\nNgày sinh: "+edtBirthday.getText().toString()+"\nEmail:"+edtEmail.getText().toString(); txtShowMessage.setText(str); txtShowMessage.setBackgroundColor(Color.GREEN); } }); } }
Ứng dụng này được phát triển bởi adt bundle, android 4.2 sử dụng minimum sdk 11 and target sdk 21.
Kết quả khi chạy ứng dụng:
Sau đó điền thông tin và Click vào Button "Đăng Ký":
Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com