Hiển thị các bài đăng có nhãn tài liệu. Hiển thị tất cả bài đăng

Học lập trình Android - Tạo Custom ListView

Với những bài học trước của khóa học lập trình android cơ bản, chúng ta đã bước đầu làm quen đc với control ListView . 
Trong những ví dụ cơ bản thì ta có thể sử dụng trực tiếp ListView do android cung cấp. Nhưng trên thực tế, khi chúng ta muốn tạo ListView theo yêu cầu thì việc sử dụng ListView của android lại không hiệu quả. Do đó, hôm nay chúng ta sẽ học cách Custom ListView theo ý muốn của mình.
Hãy cùng xét một ví dụ để thấy rõ được sự khác biệt khi chúng ta sử dụng ListView có sẵn và Custom ListView.
Giới thiệu du lịch việt nam (hiện thị danh sách các danh nhân). Giao diện chính của chương trình (thiết kế giao diện và xử lý button chúng tôi sẽ đề cập ở một bài khác):

Khi bạn nhân vào nút Vietnamese trên giao diện sẽ hiện ra danh sách như sau:

Với danh sách hiện thị này chúng ta sẽ so sánh kết quả đạt được khi ta sử dụng hai trường hợp ListView trên.

1. Sử dụng ListView có sẵn tạo giao diện cơ bản.
a. ListView với các mục không đổi
Hãy mở tập tin res/values/strings.xml và chỉnh sửa nó để chúng ta có được nội dung như sau:
Mã: <?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string name=”app_name”>VietnamTourism</string>
<string name=”menu_settings”>Settings</string>
<!– mảng các danh nhân Việt Nam –>
<string-array name=”vietnamese”>
<item >Hồ Chí Minh</item> <item >Trần Hưng Đạo</item>
<item >Ngô Bảo Châu</item> <item >Nguyễn Huệ</item>
<item >Võ Nguyên Giáp</item> <item >Hoàng Diệu</item>
<item >Đặng Thái Sơn</item> <item >Nguyễn Trãi</item>
<item >Trịnh Công Sơn</item> <item >Nguyễn Du</item>
</string-array>
</resources>

Chúng ta có một mảng chưa tên của 10 danh nhân, mảng này có tên là là Vietnamese. Chúng ta sẽ tạo giao diện cho màn hình chứa danh sách các danh nhân như hình 1.
Trong thư mục res/laout tạo tập tin activity_vietnamese.xml và nhập vào nội dung cho nó như sau:
Mã: <?xml version=”1.0″ encoding=”utf-8″?>
<ListView
xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/listViewVietnamese”
android:layout_width=”match_parent”
android:layout_height=”wrap_content” >
</ListView>
Mở tập tin này ở chế độ design (Graphical Layout) chúng ta sẽ thấy hiển thị dạng như sau:


Vẫn trong tập tin res/layout/activity_vietnamese.xml. Để chỉ định ListView này hiển thị mảng vietnamese (đã khai báo trong tập tin res/values/strings.xml ngay trên) chúng ta sử dụng thuộc tính entries của thẻ ListView như sau:
Mã: <?xml version=”1.0″ encoding=”utf-8″?>
<ListView
xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/listViewVietnamese”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:entries=”@array/vietnamese”>
</ListView>

b. Tạo mới một Activity để mở listview đã tạo sắn và mở nó thông qua Intent
Trong lập trình Android, mỗi màn hình được sử lý bởi một thành phần gọi là Activity. Ở khía cạnh lập trình, để tạo ra một Activity chúng ta tạo ra một lớp kế thừa từ lớp Activity có sẵn trong package android.app.
Trong project VietnamTourism, tạo mới một class có tên VietnameseActivity kế thừa từ lớp Activity:


Kế thừa phương thức onCreat() để có được mã nguồn:
package com.danweb.vietnamtourism;
import android.app.Activity; import android.os.Bundle;
public class VietnameseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
/*tập tin res/layout/activity_vietnamese.xml làm
layout hiển thị cho activity này*/
setContentView(R.layout.activity_vietnamese);
}}

Chúng ta phải khái báo tất cả các Activity trong cùng 1 project. Mở tập tin AndroidManifest.xml ở chế độ code, khai báo VietnameseActivity bằng thẻ <activity> nằm trong thẻ <application> như sau:
<activity android:name=”VietnameseActivity”></activity>
Để người dùng nhấn nút “Vietnammese ” trên giao diện của MainActivity sẽ thực hiện mở VietnameseActivity. Chúng ta thêm phương thức void_openVietnameseActivity() vào MainActivity:

private void _openVietnameseActivity(){/*để mở VietnameseActivity, chúng ta cần 1 đối tượng Intent gắn với lớp VietnameseActivity*/
Intent itVietnamese = new Intent(getApplicationContext(), VietnameseActivity.class);
//dùng phương thức startActivity() để thực hiện mở
startActivity(itVietnamese);
}

Trở lại phương thức onCreat(), chúng ta sử sửa chút code khi người dùng bấm vào nút Vietnamese sẽ gọi phương thức_openVietnameseActivity() này.
Mã nguồn tạm thời của class ManiActivity:

package com.danweb.vietnamtourism;
import android.os.Bundle; import android.app.Activity;
import android.content.Intent;import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomButton vietnamese = (CustomButton) findViewById(R.id.iconVietnamese);
vietnamese.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//gọi phương thức mở VietnameseActivit_openVietnameseActivity();
}
}); }
private void _openVietnameseActivity(){
/*để mở VietnameseActivity, chúng ta cần 1 đối tượng Intent gắn với lớp VietnameseActivity*/
Intent itVietnamese = new Intent(getApplicationContext(), VietnameseActivity.class);
//dùng phương thức startActivity() để thực hiện mở
startActivity(itVietnamese);
}}

c. Dữ liệu động và ListView
Trên thực tế thì chúng ta phải thường xuyên tạo ra các ListView từ các nguồn sữ liệu động (như là truy vấn từ CSDL, qua Web-service…).
Với vid dụ này chúng ta sẽ tạo một mảng động chứa các phần từ, sử dụng đối tượng ArrayAdapter để đặt dữ liệu trong mảng này lên một ListView.
Mở tập tin VietnameseActivity.java và thêm vào các nội dung để có được như sau:
package com.danweb.vietnamtourism;
import java.util.ArrayList; import android.app.Activity;
import android.content.Context; import android.os.Bundle;
import android.widget.ArrayAdapter; import android.widget.ListView;
public class VietnameseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*tập tin res/layout/activity_vietnamese.xml làm layout hiển thị cho activity này*/
setContentView(R.layout.activity_vietnamese);
//Tạo một mảng động chứa các phần tử là String
ArrayList<string> vietnamese = new ArrayList<string>();
//thêm các phần tử vào mảng động vietnamese
vietnamese.add(“Hồ Chí Minh”); vietnamese.add(“Trần Hưng Đạo”);
vietnamese.add(“Ngô Bảo Châu”); vietnamese.add(“Nguyễn Huệ”);
vietnamese.add(“Võ Nguyên Giáp”); vietnamese.add(“Hoàng Diệu”);
vietnamese.add(“Đặng Thái Sơn”); vietnamese.add(“Nguyễn Trãi”);
vietnamese.add(“Trịnh Công Sơn”); vietnamese.add(“Nguyễn Du”);
//tạo một ArrayAdapter giúp đặt dữ liệu vào ListView
Context ct= getApplicationContext();int itemView = android.R.id.text1;
int listLayout = android.R.layout.simple_list_item_1;
ArrayAdapter<string> vnAdapter = new ArrayAdapter<string>(ct, listLayout, itemView, vietnamese);
//lấy về ListView đã đặt trên activity_vietnamese.xml ListView listViewVietnamese = (ListView)findViewById(R.id.listViewVietnamese);
listViewVietnamese.setAdapter(vnAdapter); //sử dụng vnAdapter cho listViewVietnamese
}}</string></string></string></string>
Mở tập tin activity_vietnamese.xml và bỏ đi thuộc tính entries vì chúng ta không còn cần dùng đến mảng tĩnh trong tập tin strings.xml nữa: android:entries=”@array/vietnamese”

2. Tạo Custom – ListView sinh động hơn
Chúng ta sẽ tạo một giao diện sinh động hơn cho ListView ở trên, hiện thị ListView mới như hình dưới đây:


Ở ListView này, mối item có những điều khác biệt so với trước:
– Background của mỗi item nhạt dần từ dưới lên trên (gradient) tạo cảm giác các item “nổi” lên.
– Mỗi item bao gồm có 4 thành phần gồm: Hình đại diện, họ tên, năm sinh – năm mất và lĩnh vực thành danh của mỗi người.
Chúng ta có thể tạo được những hiệu ứng nhu ư trên với những khả năng Android cung cấp. Chúng ta dùng các tập tin .xml để khai báo ra các thành phần gọi là “drawable” như: hình nền (background), đường viền (stroke), ….
Tạo tập tin list_items_bg.xml trong thư mục res/drawable và nhập cho nó có nội dung như sau:
Mã: <?xml version=”1.0″ encoding=”utf-8″?>
<shape xmlns:android=”http://schemas.android.com/apk/res/android”
android:shape=”rectangle”>
<gradient
android:startColor=”#f0f0f0″
android:endColor=”#dddddd”
android:angle=”-90″/>
</shape>
ở mỗi Item trong ListView không đơn thuần chỉ là một String mà nnos bao gồm nhiều thứ hơn thế. Chúng ta sẽ xây dựng 1 class cho khái niệm danh nhân với 4 thuộc tính chúng ta đã liệt kê.
tạo lớp ListItem có code đơn giản như sau:
Mã: package com.danweb.vietnamtourism;
/*lớp tương ứng với 1 item trong ListView*/
public class ListItem {
public String name; public int photo; public String life; public String career;
public ListItem(String name, int photo, String life, String carrer)
{ this.name = name; this.photo = photo;
this.life = life; this.career = carrer;
}}

Tạo danh sách các danh nhân:
Mã:
//tạo mảng động chứa các phần tử là ListItem
ArrayList<listitem> celebrities = new ArrayList<listitem>();
//thêm các phần tử vào mảng động celebrities
celebrities.add(new ListItem(“Hồ Chí Minh”,R.drawable.hcm, “1890 – 1969″, “Revolutionary”));
celebrities.add(new ListItem(“Trần Hưng Đạo”, R.drawable.thd, “1232? – 1300″, “Commander, Poet”));
celebrities.add(new ListItem(“Ngô Bảo Châu”, R.drawable.nbc, “1972 -“, “Mathematician”));
celebrities.add(new ListItem(“Nguyễn Huệ”, R.drawable.nh, “1753 – 1792″, “Emperor”));
celebrities.add(new ListItem(“Võ Nguyên Giáp”, R.drawable.vng, “1911 -“, “Commander, Politician”));
celebrities.add(new ListItem(“Hoàng Diệu”, R.drawable.hd, “1828 – 1882″, “Governor”));
celebrities.add(new ListItem(“Đặng Thái Sơn”, R.drawable.dts, “1958 -“, “Pianist”));
celebrities.add(new ListItem(“Nguyễn Trãi”, R.drawable.nt, “1380 – 1442″, “Poet, Politician”));
celebrities.add(new ListItem(“Trịnh Công Sơn”, R.drawable.tcs, “1939 – 2001″, “Musician, Painter, Poet”));
celebrities.add(new ListItem(“Nguyễn Du”, R.drawable.nd, “1766 – 1820,”, “Poet”));
</listitem></listitem>
Các bạn chú ý, nhớ add hình ảnh các danh nhân vào thư mục Drawable
Chúng ta sẽ phải trinh bày bố cục cho 1 item trong ListView có đầy đủ 4 phần như nhận xét, dó đó chúng ta phài tạo một layout có bố cục 4 phần như sau:
Mã:
<?xml version=”1.0″encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent” android:layout_height=”wrap_content”
android:background=”@drawable/list_items_bg”android:orientation=”horizontal” <ImageView
android:layout_width=”0dp” android:layout_weight=”1″
android:padding=”5dp” android:layout_height=”match_parent”
android:id=”@+id/itemPhoto” android:src=”/@drawable/tcs” />
<LinearLayout
android:layout_width=”0dp” android:layout_weight=”4″
android:layout_height=”wrap_content” android:padding=”5dp”
android:orientation=”vertical”>
<TextView
android:id=”@+id/itemName” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:text=”Name” android:textAppearance=”?android:attr/textAppearanceLarge” />
<TextView
android:id=”@+id/itemCarrer” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:text=”Carrer”
android:textAppearance=”?android:attr/textAppearanceSmall” />
<TextView
android:id=”@+id/itemLife” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:text=”Life”
android:textAppearance=”?android:attr/textAppearanceSmall” />
</LinearLayout>
</LinearLayout>

Nếu ở chế độ design mà cho sự hiện thi như hình bên dưới thì chúng ta đã thành công:


Trên thực tế để hiển thị như hình, thì chúng ta cần xây dựng lớp View tương ứng co mỗi item trên ListView. Để làm được điều này hãy tạo một lớp mới có tên VietnameseView kế thừ từ lớp LinearLayout như sau:


Với lớp này, chúng ta viết code như sau:
package com.danweb.vietnamtourism;
import android.app.Service; import android.content.Context;
import android.view.LayoutInflater; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.TextView;
/*lớp tương ứng với 1 item trên Custom-ListView */
public class VietnameseView extends LinearLayout {
//các thuộc tính tương ứng với các View Widget trong tập tin list_item.xml
public ImageView photo; public TextView name;
public TextView life; public TextView carrer;
public VietnameseView(Context context) {
super(context);
//đọc tập tin list_item.xml để lấy các thành phần
LayoutInflater linflater = (LayoutInflater((VietnameseActivity)context).getSystemService(Service.LAYOUT_INFLATER_SERVICE);
linflater.inflate(R.layout.list_item, this);
//lấy các thành phần tương ứng
this.photo = (ImageView) findViewById(R.id.itemPhoto);
this.name = (TextView) findViewById(R.id.itemName);
this.life = (TextView) findViewById(R.id.itemLife);
this.carrer = (TextView) findViewById(R.id.itemCarrer);}
/* phương thức đặt data vào trong phần tử VietnameseView@param item */
public void setListItem(ListItem item){
this.photo.setImageResource(item.photo);this.name.setText(item.name);
this.life.setText(item.life);this.carrer.setText(item.career);
}}

Như chúng ta đã làm trong phần trên, để đặt một ArrayList<String> lên trang thì chúng ta đã sử dụng một ArrayAdapter<String>. Tương tự, để đặt một ArrayList<ListItem> lên trang thì chúng ta cần có một ArrayAdapter<ListItem>, đây là một lớp chưa có sẵn và chúng ta phải đi tạo ra nó. Lớp này như ta đã biết có nhiệm vụ là đặt các phần tử trong mảng lên trên ListView.
Tạo lớp VietnameseAdapter kế thừa từ lớp có sẵn ArrayAdapter như sau:


Chúng ta viết code như sau:
package com.danweb.vietnamtourism;
import java.util.List; import android.content.Context;
import android.util.Log; import android.view.View;
import android.view.ViewGroup; import android.widget.ArrayAdapter;
public class VietnameseAdapter extends ArrayAdapter<listitem> {
private List<listitem> _listItems; private Context _context;
public VietnameseAdapter(Context context, inttextViewResourceId,List<listitem> objects)
{super(context, textViewResourceId, objects);
this._context = context;this._listItems = objects;}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{VietnameseView view = new VietnameseView(this._context);
view.setListItem(this._listItems.get(position));return view;}}
</listitem></listitem></listitem>

Ở lớp VietnameseAdapter này chúng ta cần chú ý nhất là phương thức getView(), đây là phương thức được Android gọi thực thi để hiển thị item lên ListView khi duyệt qua mảng chứa dữ liệu cần hiển thị (trong trường hợp này là this._listItems).Tham số đầu tiên position chính là vị trí của phần tử dữ liệu hiện thời. Như vậy, mỗi lần Android gọi phương thức getView() chúng ta có thể dựa vào tham số position mà nó truyền vào để biết cần phải hiển thị nội dung tương ứng gì.

Đến đây chúng ta đã tạo ra các thành phần Custom như:
- ListItem: lớp đối tượng mà mỗi đối tượng chứa dữ liệu của một item cần hiển thị (giống String trong trường hợp ListView thông thường).
- VietnameseView: lớp đối tượng xử lý đọc tập tin list_item.xml để trình bày giao diện cho mỗi item trong ListView.
- VietnameseAdapter: lớp đối tượng kết nối giữa ListView với mảng chứa các Listitem (giống lớp ArrayAdapter trong trường hợp ListView thông thường).
Bây giờ, quay lại tập tin VietnameseActivity, sửa lại mã nguồn như sau:

//tạo một đối tượng adapter mới tạo
VietnameseAdapter newAdapter = new VietnameseAdapter(this,listViewVietnamese.getId(), celebrities);
//sử dụng newAdapter cho listViewVietnamese
listViewVietnamese.setAdapter(newAdapter);
Toàn bộ mã code lớp VietnameseActivity:
package com.danweb.vietnamtourism;
import java.util.ArrayList; import android.app.Activity;
import android.content.Context; import android.os.Bundle;
import android.widget.ArrayAdapter; import android.widget.ListView;
public class VietnameseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*tập tin res/layout/activity_vietnamese.xml làm
layout hiển thị cho activity này*/
setContentView(R.layout.activity_vietnamese);
//tạo mảng động chứa các phần tử là ListItem
ArrayList<listitem> celebrities = new ArrayList<listitem>();
//thêm các phần tử vào mảng động celebrities
celebrities.add(new ListItem(“Hồ Chí Minh”, R.drawable.hcm, “1890 – 1969″, “Revolutionary”));
celebrities.add(new ListItem(“Trần Hưng Đạo”,R.drawable.thd, “1232? – 1300″, “Commander, Poet”));
celebrities.add(new ListItem(“Ngô Bảo Châu”, R.drawable.nbc, “1972 -“, “Mathematician”));
celebrities.add(new ListItem(“Nguyễn Huệ”, R.drawable.nh, “1753 – 1792″, “Emperor”));
celebrities.add(new ListItem(“Võ Nguyên Giáp”, R.drawable.vng, “1911 -“, “Commander, Politician”));
celebrities.add(new ListItem(“Hoàng Diệu”, R.drawable.hd, “1828 – 1882″, “Governor”));
celebrities.add(new ListItem(“Đặng Thái Sơn”,R.drawable.dts, “1958 -“, “Pianist”));
celebrities.add(new ListItem(“Nguyễn Trãi”,R.drawable.nt, “1380 – 1442″, “Poet, Politician”));
celebrities.add(new ListItem(“Trịnh Công Sơn”, R.drawable.tcs, “1939 – 2001″, “Musician, Painter, Poet”));
celebrities.add(new ListItem(“Nguyễn Du”, R.drawable.nd, “1766 – 1820,”, “Poet”));
//lấy về ListView đã đặt trên activity_vietnamese.xml
ListView listViewVietnamese = (ListView)findViewById(R.id.listViewVietnamese);
//tạo một đối tượng adapter mới tạo
VietnameseAdapter newAdapter = new VietnameseAdapter(this, listViewVietnamese.getId(), celebrities);
//sử dụng newAdapter cho listViewVietnamese
listViewVietnamese.setAdapter(newAdapter);
}}
</listitem></listitem>
Như vậy chúng ta đã tìm hiểu khái quát xong về ListView và Custom ListView, tuy nội dụng còn khá đơn giản nhưng hy vọng cũng đã có thể hiểu được phần nào về khái niệm quan trọng này khi học lập trình Android.
Nguôn : danweb.vn

Học lập trình android - Control ListView trong android 2

Khóa học lập trình Android cơ bản tại ITP Việt Nam là khóa học cung cấp những kiến thức cơ bản và nâng cao về lập trình ứng dụng android, mở ra cho các bạn học viên một sự lựa chọn cơ hội việc làm mới.Ở bài trước, chúng ta đã tìm hiều về một phần về những trường hợp sử dụng Control ListView, với bài viết hôm nay chúng ta sẽ hoàn thiện kiến thức của bài hôm trước.

4. Sử dụng ArrayList và ListView nhưng từng phần tử trong ArrayList là các Object bất kỳ
Hiển thị danh sách nhân việ theo sơ đồ sau:

ListView trong android - khóa học lập trình android cơ bản

– Có 2 loại nhân viên : Nhân viên chính thức (EmployeeFullTime ) và nhân viên thời vụ (EmployeePartime).
– Mỗi nhân viên sẽ có cách tính lương khác nhau (tên phương thức tính lương giống nhau)
– Mỗi nhân viên có phương thức toString để xuất thông tin, Nội dung xuất khác nhau. Thêm FullTime đằng sau Id và Name đối với nhân viên chính thức. Thêm Partime đằng sau Id và Name đối với nhân viên thời vụ.
– Xem giao diện chương trình:

ListView trong android - khóa học lập trình android cơ bản

– Tạo một Android Project tên: Vidu_ListView_ArrayList_Object, cấu trúc như bên dưới:

ListView trong android - khóa học lập trình android cơ bản

– Layout XML (activity_main.xml):
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/LinearLayout1″ android:layout_width=”match_parent”
android:layout_height=”match_parent” android:orientation=”vertical”
tools:context=”.MainActivity” >
<TextView
android:id=”@+id/textView1″ android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:background=”#008000″
android:gravity=”center”
android:text=”Quản lý nhân viên” android:textColor=”#FFFFFF”
android:textSize=”20sp” />
<TableLayout
android:layout_width=”match_parent” android:stretchColumns=”*”
android:layout_height=”wrap_content” >
<TableRow
android:id=”@+id/tableRow1″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >
<TextView
android:id=”@+id/textView2″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Mã NV:” />
<EditText
android:id=”@+id/editMa” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_span=”2″
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/textView3″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Tên NV:” />
<EditText
android:id=”@+id/editTen” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_span=”2″
android:ems=”10″ /> </TableRow>
<TableRow
android:id=”@+id/tableRow3″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >
<TextView
android:id=”@+id/textView4″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Loại NV:” />
<RadioGroup
android:id=”@+id/radiogroud1″ android:orientation=”horizontal” >
<RadioButton
android:id=”@+id/radChinhthuc” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:checked=”true” android:text=”Chính thức” />
<RadioButton
android:id=”@+id/radThoivu” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Thời vụ” />
</RadioGroup> </TableRow>
<TableRow
android:id=”@+id/tableRow4″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >
<Button
android:id=”@+id/btnnhap” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_column=”1″ android:text=”Nhập NV” />
</TableRow> </TableLayout>
<TextView
android:id=”@+id/textView5″ android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:background=”#008000″ />
<ListView
android:id=”@+id/lvnhanvien” android:layout_width=”match_parent”
android:layout_height=”wrap_content” >
</ListView> </LinearLayout>

Xây dựng các class:
– Abstract class Employee:
package tranduythanh.com;
public abstract class Employee {
private String id; private String name;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public abstract double TinhLuong();
@Override public String toString() {
// TODO Auto-generated method stub
return this.id+” – “+this.name;
}}

– class EmployeeFullTime:
package tranduythanh.com;
public class EmployeeFullTime extends Employee {
@Override public double TinhLuong() { return 500; }
@Override public String toString() {
// TODO Auto-generated method stub
return super.toString() +” –>FullTime=”+TinhLuong();
}}

– Class EmployeePartTime:
package tranduythanh.com;
public class EmployeePartTime extends Employee {
@Override public double TinhLuong() {
// TODO Auto-generated method stub
return 150;
}
@Override public String toString() {
// TODO Auto-generated method stub
return super.toString() +” –>PartTime=”+TinhLuong();
}}

Ở đây ta sẽ áp dụng tính đa hình thông qua thừa kế, chỉ cần dùng một biến có kiểu Employee, nhưng nó có thể hiểu FullTime hoặc Partime và xuất ra thông tin đúng như mình mong đợi.
Coding ở class MainActivity.java:

package tranduythanh.com;
import java.util.ArrayList; import android.os.Bundle;
import android.app.Activity; import android.view.View;
import android.view.View.OnClickListener; import android.widget.ArrayAdapter;
import android.widget.Button; import android.widget.EditText;
import android.widget.ListView; import android.widget.RadioGroup;
public class MainActivity extends Activity {
EditText editId,editName; Button btnNhap; RadioGroup radgroup; ListView lvNhanvien;
ArrayList<Employee>arrEmployee=new ArrayList<Employee>();
ArrayAdapter<Employee>adapter=null;
//Khai báo 1 employee object
Employee employee=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
editId=(EditText) findViewById(R.id.editMa); editName=(EditText) findViewById(R.id.editTen);
btnNhap=(Button) findViewById(R.id.btnnhap); radgroup=(RadioGroup) findViewById(R.id.radiogroud1);
lvNhanvien=(ListView) findViewById(R.id.lvnhanvien);
//đưa Data Source là các employee vào Adapter
adapter=new ArrayAdapter<Employee>(this, android.R.layout.simple_list_item_1, arrEmployee);
lvNhanvien.setAdapter(adapter); //đưa adapter vào ListView
btnNhap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
processNhap();
} });
}
//Xử lý sự kiện nhập
public void processNhap()
{ //Lấy ra đúng id của Radio Button được checked
int radId=radgroup.getCheckedRadioButtonId();
String id=editId.getText()+””;
String name=editName.getText()+””;
if(radId==R.id.radChinhthuc)
{ //tạo instance là FullTime
employee=new EmployeeFullTime();
}
else
{ //Tạo instance là Partime
employee=new EmployeePartTime();
}
//FullTime hay Partime thì cũng là Employee nên có các hàm này là hiển nhiên
employee.setId(id);
employee.setName(name);
//Đưa employee vào ArrayList
arrEmployee.add(employee);
//Cập nhập giao diện
adapter.notifyDataSetChanged();
}}

5. Sử dụng ListView nhưng dưới dạng ListActivity:
Trong trường hợp này chúng ta sẽ không cho kế thừa từ Activity nữa mà chuyển sang kế thừa từ ListActivity. Với sự kế thừa này chúng ta sẽ có cách đặt Id ccho ListView khác.
Xem giao diện:

ListView trong android - khóa học lập trình android cơ bản

Với giao diện trên thì chúng ta có cách làm XML layout sau:
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/LinearLayout1″ android:layout_width=”match_parent”
android:layout_height=”match_parent” android:orientation=”vertical”
tools:context=”.MainActivity” >
<TextView
android:id=”@+id/selection” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:background=”#008000″
android:textColor=”#FFFFFF” android:textSize=”20sp” />
<ListView
android:id=”@android:id/list” android:layout_width=”match_parent”
android:layout_height=”wrap_content” >
</ListView>
<TextView
android:id=”@android:id/empty” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:text=”Không có gì cả” />
</LinearLayout>

Trong đoạn lệnh này thì dòng lệnh 18: android:id=”@android:id/list“ và dòng lệnh 24: android:id=”@android:id/empty“ là những lệnh được định nghĩa sẵn trong android, dùng để định nghĩa một id và tự động thông báo khi ListView không có bất kì một phần tử nào.
Bây giờ chúng ta sẽ xét class MainActivity.java:

package tranduythanh.com;
import android.os.Bundle; import android.app.ListActivity;
import android.view.View; import android.widget.ArrayAdapter;
import android.widget.ListView; import android.widget.TextView;
public class MainActivity extends ListActivity {
TextView selection;
String arr[]={“Intel”,”SamSung”, “Nokia”,”Simen”,”AMD”, “KIC”,”ECD”};
ArrayAdapter<String >adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//Thiết lập Data Source cho Adapter
adapter=new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, arr);
//Gán Adapter vào ListView
//Nhớ là phải đặt id cho ListView theo đúng quy tắc
setListAdapter(adapter); selection=(TextView) findViewById(R.id.selection);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String txt=”postion = “+position +”; value =”+arr[position]; selection.setText(txt);
}}

Bạn nhìn vào dòng lệnh số 10: đây là kế thừa từ ListActivity (Android đã viết class ListActivity kế thừa từ Activity rồi). Tức là ListActivity cũng chính là Activity.
Dòng lệnh số 28: setListAdapter(adapter); ListView cũng tự động cập nhập dữ liệu. Điều kiện để làm được:
- Kết thừa từ ListActivity,
- đặt id cho ListView theo đúng quy tắc android:id=”@android:id/list”
Trên đây là 5 trường hợp cơ bản sử dụng ListView. Các bạn hãy cố gắng làm lại thật nhiều lần để có thể hiểu sâu sắc hơn về nó nhé.

Học lập trình android - Control ListView trong Android 1

Trong list bài hướng dẫn Học lập trình Android cơ bản thì không thể bỏ qua phần kiến thức về control ListView. Đây là một control quan trọng được sử dụng rất nhiều khi lập trình ứng dụng android.
Trong một ứng dụng bạn cần lưu trữ và hiển thị danh sách các thông tin thì chúng ta sử dụng control ListView. ListView được dùng để hiện thị các danh sách, được truyền vào từ các đối tượng được gọi ra bởi các lớp trong Android.
Với mức độ tìm hiểu các vị dụ đơn giản thì chúng ta chỉ cần sử dụng ListView có sẵn của Android là được. Hôm nay chúng ta sẽ xét 5 trường hợp sử dụng ListView và đây cũng là những cách ta xây dựng listview khác nhau:

1. Sử dụng ListView control với mảng dữ liệu định sẵn:
Xét ví dụ đơn giản: hiện thị mảng dữ liệu lên trên ListView. Giao diện như hình sau:

Với giao diện trên chúng ta sử dụng 2 control:
– ListView: dùng để hiển thị mảng dữ liệu
– TextVew (có màu xanh lục): dùng để hiển thị vị trí và giá trị của phần tử được chọn trong ListView
Bạn tạo một android project: Vidu_ListView_HardCode_Array, lựa chọn layout phù hợp và kéo thả các control vào giao diện:


Dưới đây là nội dung của activity_main.xml:

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/LinearLayout1″
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
tools:context=”.MainActivity” >
<TextView
android:id=”@+id/txtselection”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”#dd0230dd”
android:hint=”Selected person here” />
<ListView
android:id=”@+id/lvperson”
android:layout_width=”match_parent”
android:layout_height=”wrap_content” >
</ListView>
</LinearLayout>


Đặt id cho ListView là lvperson, chúng ta có thể định dạng thêm một số đặc tính khác, với mức độ cơ bản thì chúng ta chỉ cần hiển thị được dữ liệu lên giao diện.
Sau đây là code chúng ta xử lý trong MainActivity.java:

package tranduythanh.com;
import android.os.Bundle; import android.app.Activity;
import android.view.View; import android.widget.AdapterView;
import android.widget.ArrayAdapter; import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1. Khởi tạo dữ liệu cho mảng arr (còn gọi là data source)
final String arr[]={“Teo”,”Ty”,”Bin”,”Bo”};
//2. Lấy đối tượng Listview dựa vào id
ListView lv=(ListView) findViewById(R.id.lvperson);
//3. Gán Data source vào ArrayAdapter
ArrayAdapter<String>adapter=new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, arr);
//4. Đưa Data source vào ListView lv.setAdapter(adapter);
final TextView txt=(TextView) findViewById(R.id.txtselection);
//5. Thiết lập sự kiện cho Listview, khi chọn phần tử nào thì hiển thị lên TextView
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//đối số arg2 là vị trí phần tử trong Data Source (arr)
txt.setText(“position :”+arg2+” ; value =”+arr[arg2]);
}});
}}


Chú ý trong đoạn code chúng ta sẽ giải thích vè lệnh ArrayAdapter:
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this, adroid.R.layout.simple_list_item_1, arr);
Giải thích: dữ liệu từ Data source (arr) sẽ được gắn vào ArrayAdapter, ArrayAdapter sẽ gắn vào ListView. Đối số đầu tiên của constructor ArrayAdapter : this, chính là context của Activity hiện tại, bạn có thể viết MainActivity.this (nếu bạn viết như thế này thì ở bất kỳ vị trí nào nó cũng hiểu là context của MainActivity, do đó các bạn nên viết như thế này để bạn có thể copy paste nó tới bất kỳ vị trí nào thì nó cũng hiểu). Đối số thứ 2 android.R.layout.simple_list_item_1: đây là layout ListView của Android xây dựng sẵn, đối số này được lưu trữ trong SDK/platform/android-ap (x)/data/res/layout/simple_list_item_1.xml.
Đối số thứ 3 chính là arr (data source), bạn có thể truyền vào ArrayList.
Ngoài ra chúng ta có interface AdapterView.OnItemClickListener, nó dùng để thiết lập sự kiện cho listview, interface này có 1 phương thức trừu tượng là onItemClick nên ta override nó về xử lý trong này. Để mở chúng ta nhấn tổ hợp phím Ctrl + 1chọn add unimplement method là nó tự xuất hiện

2. Sử dụng ListView với mạng dữ liệu được lưu trong XML:
Giao diện và xử lý sự kiện trong trường hợp này là y xì trường hợp 1. Chỉ khác ở chỗ là dữ liệu sẽ được load từ XML, nên Tôi chỉ hướng dẫn cách tạo String – Array trong XML và cách load String-Array trong coding như thế nào.
Tạo 1 Android Project tên là: Vidu_ListView_Xml_Array
Bước 1: Bấm chuột phải vào thư mục values của Project/ chọn New/Android XML File:


Bước 2: Màn hình New Android XML hiển thị lên, bạn chọn thông số giống như hình bên dưới, đặt tên tập tin là mystrings.xml rồi nhấn nút Finish:


Kểt quả khi bấm nút Figgisn và ta có kết quả:


Chúng ta có thể thêm dữ liệu vào tệp tin nhưng chúng tôi muốn hướng dẫn các bạn tạo 1 tệp XML mới và thêm dữ liệu vào đó.
Bước 3: chọn tab Resource ở hình trên:


Bước 4: Bấm nút “Add…” ở màn hình trên để thêm String-Array:


Bước 5: Đặt tên cho String Array, sau khi nhấn OK thì màn hình bên dưới hiển thị ra, bạn đặt tên String Array này là myarray rồi nhấn ctrl+s để lưu:


Bước 6: Thêm các phần tử vào String Array, tiếp tục bấm nút Add ở màn hình bên trên:


- Sau khi nhấn OK thì nó sẽ cho phép bạn nhập giá trị cho phần tử.

- Bạn cứ lặp liên tục thao tác ở bước 6 này, thêm bao nhiêu phần tử thì click từng đó lần Add, ở đây là Tôi thêm 3 phần tử, bạn xem hình:


– Xem nội dung XML:

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string-array name=”myarray”>
<item >Trần Văn Tèo</item>
<item >Nguyễn Thị Tẹt</item>
<item >Hồ Văn Hiến</item>
</string-array>
</resources>

Đã tạo xong một tập tin XML và biết cách tạo String Array cũng như các phần tử nằm trong đó. Bây giòe chings ta sẽ dựa vào myarray để đọc toàn bộ dữ liệu (myarray khi bạn tạo ra ở trên thì nó cũng được tạo ra trong gen)
Mở MainActivity lên: code tương tự trường hợp 1, chỉ khác chúng ta sử dụng lệnh đọc dữ lieeujtuwf XML đổ về 1 mảng: final String arr[]=getResources().getStringArray(R.array.myarray) (thay dòng 17 ở trường hợp 1 của MainActivity bằng dòng lệnh trên.)

3. Sử dụng ArrayList và Listview control:
Hướng dẫn cách sử dụng ArrayList để lưu trữ dữ liệu và đổ lên ListView như thế nào, bạn xem giao diện của chương trình:


Mô tả:
+ Nhập dữ liệu và nhấn nút “Nhập” thì sẽ đưa vào ArrayList và hiển thị lên ListView
+ Nhấn vào phần tử nào thì hiển thị vị trí và giá trị của phần tử đó lên TextView
+ Nhấn thật lâu (long click ) vào phần tử nào đó trên ListView thì sẽ xóa phần tử đó.
Tạo Android Project tên: Vidu_ListView_ArrayList,
Xem Layout XML của ứng dụng (activity_main.xml):

<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” >
<EditText
android:id=”@+id/txtTen” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_alignParentTop=”true”
android:inputType=”text” android:layout_toRightOf=”@+id/textView1″ android:ems=”10″ />
<TextView
android:id=”@+id/textView1″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_alignBaseline=”@+id/txtTen”
android:layout_alignBottom=”@+id/txtTen” android:layout_alignParentLeft=”true”
android:background=”#deb887″ android:text=”Nhập tên:” />
<Button
android:id=”@+id/btnNhap” android:layout_width=”wrap_content”
android:layout_height=”wrap_content” android:layout_alignRight=”@+id/txtTen”
android:layout_below=”@+id/txtTen” android:layout_toRightOf=”@+id/textView1″
android:textAlignment=”center” android:text=”Nhập” />
<TextView
android:id=”@+id/txtselection” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:layout_alignParentLeft=”true
android:layout_below=”@+id/btnNhap” android:background=”#007380″ />
<ListView
android:id=”@+id/lvperson” android:layout_width=”match_parent”
android:layout_height=”wrap_content” android:layout_alignParentLeft=”true”
android:layout_below=”@+id/txtselection” android:background=”#cccccc” >
</ListView>
</RelativeLayout>

Xem MainActivity.java:

package tranduythanh.com;
import java.util.ArrayList; import android.os.Bundle;
import android.app.Activity; import android.view.View;
import android.widget.AdapterView; import android.widget.ArrayAdapter;
import android.widget.Button; import android.widget.EditText;
import android.widget.ListView; import android.widget.TextView;
public class MainActivity extends Activity {
EditText txtten; TextView txtchon;
Button btn; ListView lv;
ArrayList<String>arrList=null; ArrayAdapter<String> adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
txtten=(EditText) findViewById(R.id.txtTen); txtchon=(TextView) findViewById(R.id.txtselection);
lv=(ListView) findViewById(R.id.lvperson);
//1. Tạo ArrayList object
arrList=new ArrayList<String>();
//2. Gán Data Source (ArrayList object) vào ArrayAdapter
adapter=new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, arrList);
//3. gán Adapter vào ListView
lv.setAdapter(adapter);
btn=(Button) findViewById(R.id.btnNhap);
//4. Xử lý sự kiện nhấn nút Nhập
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) { arrList.add(txtten.getText()+””); adapter.notifyDataSetChanged(); }
});
//5. Xử lý sự kiện chọn một phần tử trong ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick( AdapterView<?> arg0,View arg1, int arg2,long arg3) {
txtchon.setText(“position : “+ arg2+ “; value =”+arrList.get(arg2)); }
});
//6. xử lý sự kiện Long click
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arrList.remove(arg2);//xóa phần tử thứ arg2
adapter.notifyDataSetChanged();
return false; }
});}}


Giải thích code:
– hàm adapter.notifyDataSetChanged(); Bạn chú ý là ArrayList được gán vào adapter nên mọi sự thay đổi trong ArrayList thì adapter đều nhận biết được. Khi có sự thay đổi trong ArrayList bạn chỉ cần gọi notifyDataSetChanged thì ListView sẽ được cập nhật (bởi vì Adapter được gắn vào ListView).
– Sự kiện setOnItemLongClickListener, được gắn cho ListView Item, khi nhấn lâu từ 2.5 tới 3 giây thì sự kiện này sẽ sảy ra. Tương tự như setOnItemClickListener , đối số có tên arg2 được dùng để xác định được vị trí của phần tử nằm trong ArrayList.

Checkbox và RadioButton - học lập trình android cơ bản

Tiếp tục hôm nay chúng ta sẽ tìm hiểu cách sử dụng CheckBox và RadioButton. Đây cũng là hai control thường xuyên được sử dụng trong các chương trình. Kết thúc bài hôm nay là chúng ta đã tìm hiểu xong các control cơ bản nhất phục vụ học lập trình android và phục vụ cho việc lập trình của các bạn sau này. 
Bắt đầu tìm hiểu nào.

1. Khái niệm và cách sử dụng
CheckBox là control dùng để chuyển đổi trạng thái giữa yes/no/true/false. Khi state là true thì ô được đánh dấu.
RadioButton là một nút chọn, ở đây nó thể hiện nhiều sự lựa chọn khác nhau, người dùng ấn vào một hoặc nhiều nút tương ứng với các lựa chọn của họ.
Trong Android thì CheckBox và RadioButton đều sử dụng chung 2 phương thức:
– Phương thức setChecked, dùng để thiết lập checked. Nếu ta gọi setChecked (true) tức là cho phép control được checked, con gọi setChecked (fasle) thì control sẽ bị unchecked.
– Phương thức isChecked, kiển tra xem control có được checked hay không. Nếu có checked thì trả về true ngược lại trả về fasle.
Tuy sử dụng cùng phương thức nhưng hai control này có sự khác biệt: Checkbox cho phép ta checked nhiều đối tượng, còn RadioButton thì tại một thời điển nó chỉ cho ta checked 1 đối tượng trong cùng một group mà thôi.
Nếu muốn sử dụng nhiều lựa chọn thì bạn nên sử dụng checkbox, ví dụ ở hình bên dưới:

control android cơ bản-học lập trình android


Ta có thể thiết lập cho Checkbox bất kỳ được checked mặc định trong XML:



Trong coding để kiểm tra xem Checkbox đó có được checked hay không thì chúng ta xử lý như sau:

control android cơ bản-học lập trình android

Nếu bạn muốn người dùng chỉ được chọn 1 lựa chọn trong nhiều loại lựa chọn đưa ra thì bạn nên sử dụng RadioButton, ví dụ hình dưới đây:

control android cơ bản-học lập trình android

Tương tự như Checkbox, chúng ta có thể thiết lập checked cho RadioButton bất kỳ trong XML:

control android cơ bản-học lập trình android

Nhìn vào đoạn thiết lập trên , chúng ta phải sử dụng RadioGroup để gom nhóm các Radiobuton lại cùng một nhóm nào đó, những RadioButton mà cùng một nhóm thì tại 1 thời điểm chỉ có 1 RadioButton được checked mà thôi. Có thể tạo nhiều nhóm RadioButtonGroup trong một màn hình.
Chúng ta có hai cách xử lý RadioButton như sau:
Cách 1: dựa vào RadioButton để biết chính xác Id của Radiobutton nào được checked. Dựa vào id này ta sẽ xử lý:

control android cơ bản-học lập trình android

Trong đoạn xử lý trên, hàm getCheckedRadioButton(): hàm này trả về ID của RadioButton nằm trong RadioGroup 1 được checked. Dựa vào Id này bạn so sánh để biết được trên giao diện người sử dụng đang check lựa chọn nào.
Cách 2: kiểm tra trực tiếp RadioButton đó có được check hay không?

control android cơ bản-học lập trình android


Cách xử lý khác nhau nhưng có chung một mục đích. Để xóa bỏ check trong group (dù sử dụng cách 1 hay cách 2) thì ta sử dụng lệnh:  group.clearChecked();  //với group là đối tượng RadioGroup.

2. Ví dụ minh họa
Bây giờ chúng ta sẽ xét một ví dụ kết hợp giữa RadioButton và CheckBox để các bạn hiểu sâu hơn về 2 control này. Giao diện như hình dưới đây:

control android cơ bản-học lập trình android


Mô tả giao diện:
– Tên người không được để trống và phải có ít nhất 3 ký tự
– Chứng minh nhân dân chỉ được nhập kiểu số và phải có đúng 9 chữ số
– Bằng cấp mặc định sẽ chọn là Đại học
– Sở thích phải chọn ít nhất 1 chọn lựa
– Thông tin bổ sung có thể để trống
– Khi bấm gửi thông tin, chương trình sẽ hiển thị toàn bộ thông tin cá nhân cho người sử dụng biết (dùng Alert Dialog):

control android cơ bản-học lập trình android

Sau đây là code trong MainActivity:
package tranduythanh.com;
import android.os.Bundle; import android.app.Activity;
import android.app.AlertDialog; import android.content.DialogInterface;
import android.view.Menu; import android.view.View;
import android.widget.Button; import android.widget.CheckBox;
import android.widget.EditText; import android.widget.RadioButton;
import android.widget.RadioGroup; import android.widget.Toast;
public class MainActivity extends Activity {
EditText editTen,editCMND,editBosung;
CheckBox chkdocbao,chkdocsach,chkdoccode;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTen=(EditText) findViewById(R.id.editHoten);
editCMND=(EditText) findViewById(R.id.editCMND);
editBosung=(EditText) findViewById(R.id.editBosung);
chkdocbao=(CheckBox) findViewById(R.id.chkdocbao);
chkdoccode=(CheckBox) findViewById(R.id.chkdoccoding);
chkdocsach=(CheckBox) findViewById(R.id.chkdocsach);
Button btn=(Button) findViewById(R.id.btnguitt);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stubdoShowInformation();}
});}
public void doShowInformation()
{//Kiểm tra tên hợp lệ
String ten=editTen.getText()+””; ten=ten.trim();
if(ten.length()<3)
{editTen.requestFocus(); editTen.selectAll();
Toast.makeText(this, “Tên phải >= 3 ký tự”, Toast.LENGTH_LONG).show();
return;}
//kiểm tra CMND hợp lệ
String cmnd=editCMND.getText()+””; cmnd=cmnd.trim();
if(cmnd.length()!=9)
{ editCMND.requestFocus(); editCMND.selectAll();
Toast.makeText(this, “CMND phải đúng 9 ký tự”, Toast.LENGTH_LONG).show();
return;}
//Kiểm tra bằng cấp
String bang=””;
RadioGroup group=(RadioGroup) findViewById(R.id.radioGroup1);
int id=group.getCheckedRadioButtonId();
if(id==-1)
{ Toast.makeText(this, “Phải chọn bằng cấp”, Toast.LENGTH_LONG).show();
return;}
RadioButton rad=(RadioButton) findViewById(id); bang=rad.getText()+””;
//Kiểm tra sở thích
String sothich=””;
if(chkdocbao.isChecked()) sothich+=chkdocbao.getText()+”\n”;
if(chkdocsach.isChecked()) sothich+=chkdocsach.getText()+”\n”;
if(chkdoccode.isChecked())
sothich+=chkdoccode.getText()+”\n”; String bosung=editBosung.getText()+””;
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle(“Thông tin cá nhân”);
builder.setPositiveButton(“Đóng”, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();}});
//tạo nội dung
String msg=ten+”\n”; msg+= cmnd+”\n”; msg+=bang+”\n”;
msg+=sothich; msg+=”—————————–\n”;
msg+=”Thông tin bổ sung:\n”; msg+=bosung+ “\n”;
msg+=”—————————–“; builder.setMessage(msg);//thiết lập nội dung
builder.create().show();//hiển thị Dialog
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}

Trên đây chúng tôi đã giới thiệu sơ lược xong về 2 control cơ bản còn lại cùng các bạn, chắc hẳn các bạn cũng đã hiểu được phần nào đó về Checbox và Radiobutton rồi nhỉ ^_^.

Copyright © 2013 ĐÀO TẠO LẬP TRÌNH TẠI HÀ NỘI and Blogger Templates - Anime OST.