Trong bài này, bạn sẽ xem xét các view cơ bản trong Android cho phép bạn hiển thị thông tin văn bản cũng như thực hiện một số lựa chọn cơ bản. Đặc biệt, bạn sẽ tìm hiểu về các view sau đây:
Khi bạn tạo một Project Android, Eclipse luôn luôn tạo ra các file main.xml(nằm trong res/layout) có chứa <TextView>:
PHP:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
- TextView
- EditText
- Button
- ImageButton
- CheckBox
- ToggleButton
- RadioButton
- RadioGroup
Khi bạn tạo một Project Android, Eclipse luôn luôn tạo ra các file main.xml(nằm trong res/layout) có chứa <TextView>:
PHP:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
TextView được sử dụng để hiển thị văn bản cho người dùng. Đây là view cơ bản nhất mà bạn chắc chắn sẽ phải dùng qua khi bạn phát triển ứng dụng Android. Nếu bạn cần phải cho phép người dùng chỉnh sửa các văn bản hiển thị, bạn nên sử dụng lớp con của TextView là EditText, được đề cập đến trong phần tiếp theo. Bên cạnh TextView, cái mà bạn sẽ thường xuyên dùng nhất, có một số điều khiển cơ bản khác mà bạn sẽ sử dụng rất thường xuyên, Đó là: Button, ImageButton, EditText, CheckBox, ToggleButton, Radiobutton, và RadioGroup. Đầu tiên, thêm một file mới vào res/layout là basicviews.xml. Nó thường sử dụng các phần tử sau:
PHP:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
Quảng cáo
<Button android:id="@+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
<Button android:id="@+id/btnOpen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open"
/>
<ImageButton android:id="@+id/btnImg1"
Quảng cáo
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/icon"
/>
<EditText android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<CheckBox android:id="@+id/chkAutosave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Autosave"
/>
<CheckBox android:id="@+id/star"
style="?android:attr/starStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioGroup android:id="@+id/rdbGp1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:eek:rientation="vertical"
>
<RadioButton android:id="@+id/rdb1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 1"
/>
<RadioButton android:id="@+id/rdb2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 2"
/>
</RadioGroup>
<ToggleButton android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Lưu ý rằng: bạn sử dụng id để xác định view. Id của view phải bắt đầu với "@+id/" ghi sau tên của view. File XML trên chứa các view sau đây:
- Button - biểu diễn nút ấn
- ImageButton - tương tự như button, ngoài ra nó hiển thị một hình ảnh
- EditText - là lớp con của TextView, ngoài ra nó cho phép người dùng chỉnh sửa nội dung văn bản của nó.
- CheckBox - một loại đặc biệt của button có hai trạng thái - checked hoặc unchecked.
- RadioGroup và Radiobutton - Radiobutton có hai trạng thái - hoặc checked hoặc unchecked. Khi một Radiobutton được checked, nó không thể unchecked. RadioGroup được sử dụng để nhóm một hoặc nhiều RadioButton lại với nhau, qua đó cho phép chỉ có một Radiobutton được checked trong RadioGroup
- ToggleButton - hiển thị trạng thái checked/unchecked bằng 1 vệt sáng
http://android.vn/attachments/8567/
PHP:
package net.learn2develop.androidviews;
import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.RadioGroup;import android.widget.Toast;import android.widget.ToggleButton;import android.widget.RadioGroup.OnCheckedChangeListener;
public class BasicViewsExample extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basicviews);
//---Button view---
Button btnOpen = (Button) findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(),
"You have clicked the Open button",
Toast.LENGTH_SHORT).show();
}
});
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
DisplayToast("You have clicked the Save button");
}
});
//---CheckBox---
CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave);
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
if (((CheckBox)v).isChecked())
DisplayToast("CheckBox is checked");
else
DisplayToast("CheckBox is unchecked");
}
});
//---RadioButton---
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
//---displays the ID of the RadioButton that is checked---
DisplayToast(Integer.toString(checkedId));
}
});
//---ToggleButton---
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle1);
toggleButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
if (((ToggleButton)v).isChecked())
DisplayToast("Toggle button is On");
else
DisplayToast("Toggle button is Off");
}
});
}
private void DisplayToast(String msg)
{
Toast.makeText(getBaseContext(), msg,
Toast.LENGTH_SHORT).show();
}
}
Đặc biệt, chương trình sẽ hiển thị trên một thông báo (bằng cách sử dụng lớp Toast) khi các view được nhấp vào. Thêm các dòng in đậm sau vào file AndroidManifest.xml để đăng kí BasicViewsExample activity:
PHP:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.androidviews"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ViewsActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BasicViewsExample"
android:label="@string/app_name" />
</application>
</manifest>
Để hiển thị Activity BasicViewsExample, thêm dòng in đậm sau vào file ViewsActivity.java:
PHP:
package net.learn2develop.androidviews;
import android.app.Activity;import android.content.Intent;import android.os.Bundle;
public class ViewsActivity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---load the BasicViewsExample activity---
startActivity(new Intent(this, BasicViewsExample.class));
}
}
Hình sau cho thấy tin nhắn hiển thị khi ToggleButton được nhấp.
http://android.vn/attachments/8568/
Muốn dùng EditText để nhập password với ký tự đại diện là "." thì đặt thuộc tính password =true như sau:
PHP:
<EditText android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password = "true"
/>
kết quả như hình dưới đây:
http://android.vn/attachments/8569/
ProgressBar View
ProgressBar cung cấp thông tin phản hồi trực quan của một số công việc. Ví dụ, bạn có thể tải một số dữ liệu từ web và cần phải cập nhật cho người dùng về tình trạng tải về. Trong trường hợp này,ProgressBar là một lựa chọn tốt cho công việc này. Sử dụng cùng một Activity tạo ra trong phần trước, thêm các yếu tố sau đây trong tập tin basicviews.xml:
PHP:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button android:id="@+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
<!-
Other views omitted
-->
</LinearLayout>
Chế độ mặc định của ProgressBar là không xác định - đó là, nó hiển thị một hành động theo chu kỳ. Chế độ này rất hữu ích cho công việc mà không có một dấu hiệu rõ ràng khi nào chúng sẽ được hoàn thành. Ví dụ, bạn sending một dữ liệu đến một dịch vụ web và chờ đợi máy chủ respond. Dòng code cho thấy cách bạn có thể tắt một tiến trình nền để mô phỏng thực hiện một số nhiệm vụ dài. Khi hoàn thành nhiệm vụ, bạn ẩn ProgressBar bằng cách setting Visibility = GONE (giá trị 8):
PHP:
import android.widget.ProgressBar;import android.os.Handler;
public class BasicViewsExample extends Activity{
private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basicviews);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
//---do some work here---
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
progressBar.setVisibility(8);
}
});
}
//---do some long lasting work here---
private int doSomeWork()
{
try {
//---simulate doing some work---
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
//...
//...
}
//...}
Sự khác biệt giữa INVISIBLE và GONE là hằng số, INVISIBLE chỉ đơn giản là ẩn ProgressBar. GONE bỏ đi ProgressBar từ Activity này và không mất bất kỳ không gian trong Activity. Bên trái của hình sau cho thấy ProgressBar trong Activity.
http://android.vn/attachments/8570/
Nếu bạn không muốn hiển thị ở chế độ ProgressBar không xác định, bạn có thể sửa đổi nó để hiển thị như một thanh ngang. Các thuộc tính phong cách sau đây xác định ProgressBar để hiển thị một horizontal bar:
PHP:
<ProgressBar android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
/>
Xem dòng code sau:
PHP:
public class BasicViewsExample extends Activity{
private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basicviews);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
while (progressStatus < 100)
{
progressStatus = doSomeWork();
//---Update the progress bar---
handler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run() {
//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
progressBar.setVisibility(8);
}
});
}
private int doSomeWork()
{
try
{
//---simulate doing some work---
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
//...
//...
}
}
http://android.vn/attachments/8571/
AutoCompleteTextView View
AutoCompleteTextView là một view tương tự như xem EditText (trên thực tế nó là một lớp con của EditText), ngoại ra nó hiển thị một danh sách các đề xuất hoàn thành tự động trong khi người dùng đang gõ. Thêm một file mới vào res/layout là autocomplete.xml như sau:
PHP:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<AutoCompleteTextView android:id="@+id/txtCountries"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Thêm vào project lớp "AutoCompleteExample" như sau:
PHP:
package net.learn2develop.androidviews;
import android.app.Activity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;
public class AutoCompleteExample extends Activity{
String[] presidents =
{
"Dwight D. Eisenhower",
"John F. Kennedy",
"Lyndon B. Johnson",
"Richard Nixon",
"Gerald Ford",
"Jimmy Carter",
"Ronald Reagan",
"George H. W. Bush",
"Bill Clinton",
"George W. Bush",
"Barack Obama"
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, presidents);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.txtCountries);
textView.setThreshold(3);
textView.setAdapter(adapter);
}
}
Lưu ý rằng danh sách được lấy từ một đối tượng ArrayAdapter. Phương thức setThreshold() Xác định số lượng ký tự mà người dùng phải nhập trước khi đề xuất hoàn thành được hiển thị trong một trình đơn thả xuống. Thêm các dòng sau in đậm vào file AndroidManifest.xml đăng ký hoạt động AutoCompleteExample mới:
Mã:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.androidviews"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ViewsActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AutoCompleteExample"
android:label="@string/app_name" />
</application>
</manifest>
Chỉnh sửa file ViewsActivity.java như sau:
PHP:
package net.learn2develop.androidviews;
import android.app.Activity;import android.content.Intent;import android.os.Bundle;
public class ViewsActivity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startActivity(new Intent(this, AutoCompleteExample.class));
}
}
Kết quả như sau:
http://android.vn/attachments/8572/
SummaryTrong bài viết này, chúng ta đã biết được một số view rất phổ biến mà chúng ta sẽ sử dụng trong lập trình Android. Trong hai bài báo tiếp theo, tôi sẽ đi sâu vào 1 số view nữa mà bạn có thể sử dụng trong việc xây dựng các killer Android applications của mình.