[Tự học lập trình Android] Bài 13: Tìm hiểu về GridView trong Android


Tìm hiểu về Gridview trong Android
- GridView cũng dựa vào Datasource và ArrayAdapter tương tự như ListView
- Điểm khác nhau là GridView có thiết lập số cột. Dữ liệu luôn đưa vào dưới dạng hình ống (mảng, list một chiều), nhưng dựa vào số cột ta thiết lập mà nó tự động ngắt hàng, xem hình minh họa:
Hình 1

- Gridview có thể hiển thị Text hoặc hình ảnh vào GridView.
- Bạn có thể thiết lập số cột cho GridView theo hình dưới đây:
Hình 2

- Nếu bạn thiết lập android:numColumns=”3″, Tức là Gridview sẽ ngắt dòng khi đủ 3 phần tử, nó chỉ khác chỗ này, còn việc đưa dữ liệu lên như thế nào thì nó y xì như làm với ListView.

Ví dụ 1: Hiển thị văn bản lên GridView

- Bạn tạo một Android Project tên tùy thích, ở đây Tôi đặt tên: Vidu_Gridview_Text

- Đây là activity_main.xml cho ứng dụng:

<LinearLayoutxmlns: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="#8A9D6F"
android:hint="Slected here"/>
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3">
</GridView>
</LinearLayout>


- Bạn xem dòng 15 là id của GridView, Tôi để mặc định gridView1

- Dòng 18 có thuộc tính: android:numColumns= "3″, tức là dữ liệu sẽ được hiển thị trong Gridview với định dạng 3 cột.

- Tiếp theo bạn xem MainActivity.java:

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.ArrayAdapter;
importandroid.widget.GridView;
importandroid.widget.TextView;

publicclassMainActivity extendsActivity {
//Dùng mảng 1 chiều hoặc ArrayList để lưu một số dữ liệu
String arr[]={"Ipad","Iphone","New Ipad","SamSung","Nokia","Sony Ericson","LG","Q-Mobile","HTC","Blackberry","G Phone","FPT - Phone","HK Phone"};

protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Tối tượng này dùng để hiển thị phần tử được chọn trong GridView
finalTextView selection=(TextView)findViewById(R.id.selection);
finalGridView gv=(GridView) findViewById(R.id.gridView1);
//Gán DataSource vào ArrayAdapter
ArrayAdapter<String>da=newArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
//gán Datasource vào GridView
gv.setAdapter(da);
//Thiết lập sự kiện cho GridView,
gv.setOnItemClickListener(newAdapterView.OnItemClickListener() {
publicvoidonItemClick(AdapterView<?> arg0,
View arg1, intarg2,
longarg3) {
//Hiển thị phần tử được chọn trong GridView lên TextView
selection.setText(arr[arg2]);
}
});
}
}

- Cách sử dụng GridView tương tự như ListView, nên nếu như bạn đã hiểu về ListView rồi thì GridView hiển nhiên bạn cũng làm tương tự.
- Thực thi chương trình bạn sẽ thấy như hình bên dưới:
Hình 3

Ví dụ 2: Hiển thị danh sách hình ảnh có sẵn lên GridView, mỗi lần chọn vào hình ảnh nào thì sẽ hiển thị chi tiết ảnh đó trên một màn hình mới:
- Có thể Demo này đã có nhiều website và Ebooks làm rồi, ở đây Tôi cũng muốn demo lại cho các bạn.
- Bạn xem giao diện của ứng dụng trước:
Hình 4

- Bên trái là màn hình chính cho phép hiển thị danh sách hình ảnh vào GridView, mỗi lần chọn vào từng hình trong GridView thì sẽ mở hình được chọn đó vào một màn hình mới (ví dụ như khi chọn hình chú Cừu thì nó sẽ hiển thị ra như màn hình bên phải ), nhấn nút Back để trở về màn hình chính.
- Ở đây có một sự khác biệt lớn đó là chúng ta chỉ sử dụng 1 MainActivity, không hề tạo thêm bất kỳ một Activity nào khác, chúng ta chỉ thay đổi Layout mà thôi. Nên nó cũng là điểm nhấn của ứng dụng.
-Hãy tạo một Android Project tên: Vidu_Gridview_DisplayImage và xem cấu trúc của chương trình:
Hình 5

- Layout sẽ có 2 cái: activity_main.xml là của màn hình chính dùng để hiển thị danh sách hình ảnh.solo_picture.xml là dùng để hiển thị từng hình riêng lẻ.
- Tạo thêm thư mục drawble và kéo thả một số hình ảnh vào.
- Phần class có 2 class: MainActivity và MyImageAdapter kế thừa từ BaseAdapter.
- Bây giờ ta đi vào chi tiết của từng cái:
- activity_main.xml:
Hình 6
- Bạn có thể nhìn vào hình trên để làm hoặc tải coding mẫu ở bên dưới.
-solo_picture.xml:
Hình 7
- Bây giờ ta vào các class xử lý nghiệp vụ:
Hình 8

- Thứ nhất là class MyImageAdapter:

+ class này sẽ kế thừa từ BaseAdapter, và dùng để hiển thị từng hình ảnh riêng lẻ:

importandroid.content.Context;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.GridView;
importandroid.widget.ImageView;

publicclassMyImageAdapter extendsBaseAdapter {
privateContext mContext;
privateInteger []mThumbIds;
publicMyImageAdapter(Context c){
mContext=c;
}
publicMyImageAdapter(Context c,Integer []arrIds){
mContext=c;
mThumbIds=arrIds;
}
publicintgetCount()
{
returnmThumbIds.length;
}
publicObject getItem(intarg0)
{
returnnull;
}
publiclonggetItemId(intarg0)
{
return0;
}


publicView getView(intarg0, View convertView, ViewGroup arg2) {
ImageView imgView;
if(convertView==null){
imgView=newImageView(mContext);
//can chỉnh lại hình cho đẹp
imgView.setLayoutParams(newGridView.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
}else{
imgView=(ImageView) convertView;
}
//lấy đúng vị trí hình ảnh được chọn
//gán lại ImageResource
imgView.setImageResource(mThumbIds[arg0]);
returnimgView;
}
}

- Thứ hai là class MainActivity:

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.Button;
importandroid.widget.GridView;
importandroid.widget.ImageView;
importandroid.widget.TextView;
importandroid.widget.AdapterView.OnItemClickListener;

publicclassMainActivity extendsActivity
implementsOnItemClickListener
{
TextView tvMsg;
GridView gv;
TextView tvSoloMsg;
//mảng lưu danh sách các id hình ảnh có sẵn
Integer[]mThumbIds;
//Adapter cho GridView
MyImageAdapter adapter=null;
//Vì không tạo thêm 1 Activity nên lấy luôn 2 Id ở bên solo_picture.xml
ImageView ivSoloPicture;
Button btnBack;
//Lưu Bundle backup cho MainActivity
Bundle myBackupBundle;
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Lưu savedInstanceState trước vào myBackupBundle
myBackupBundle=savedInstanceState;
setContentView(R.layout.activity_main);
tvMsg=(TextView) findViewById(R.id.tvMsg);
//gán mảng các Id hình ảnh cho mThumbIds
mThumbIds=newInteger[]{R.drawable.image1,R.drawable.image2,
R.drawable.image3,R.drawable.image4,
R.drawable.image5,R.drawable.image6,
R.drawable.ic_launcher,R.drawable.lifecycle};
gv=(GridView) findViewById(R.id.gridView1);
//thiết lập Datasource cho Adapter
adapter=newMyImageAdapter(this, mThumbIds);
//gán Adapter vào Gridview
gv.setAdapter(adapter);
//thiết lập sự kiện để mở từng hình ảnh chitiết
gv.setOnItemClickListener(this);
}
publicvoidonItemClick(AdapterView<?> arg0,View arg1, intarg2, longarg3) {
//gọi hàm xem hình ảnh chi tiết tại ví trí thứ arg2
showdetail(arg2);
}
publicvoidshowdetail(intposistion)
{
//Không mở Activity mới mà chỉ thiết lập lại Layout
setContentView(R.layout.solo_picture);
//Vừa gọi hàm trên thì màn hình sẽ thay đổi qua cái mới
//ta lấy các control trong layout mới này
tvSoloMsg=(TextView) findViewById(R.id.tvSoloMsg);
tvSoloMsg.setText("Image at "+posistion);
ivSoloPicture=(ImageView) findViewById(R.id.imgSolo);
//thiết lập hình ảnh đang chọn lên ImageView mới
ivSoloPicture.setImageResource(mThumbIds[posistion]);
btnBack=(Button) findViewById(R.id.btnBack);
//Thiết lập sự kiện click Back để phục hồi lại MainActivity
//bằng cách gọi lại onCreate(myBackupBundle);
btnBack.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View arg0) {
onCreate(myBackupBundle);
}
});
}

}

Tham khảo: duythanhcse

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------

[Tự học lập trình Android] Bài 12: Tìm hiểu về Spinner trong Android

Tìm hiểu về Spinner trong Android

- Spinner tương tự như ComboBox trong C#, tương tự như JComboBox trong Java.
- Nếu bạn đã hiểu về ListView thì việc hiểu Spinner cũng không có gì là khó.
- Cách đổ dữ liệu lên Spinner là giống như đổ lên ListView, nó chỉ khác một chỗ duy nhất trong ArrayAdapter đó là ta phải gọi setDropDownViewResource.
- Ví dụ về Spinner:
Hình 1
- Kéo 2 control: TextView và Spinner vào ứng dụng (xem activity_spinner.xml)

<LinearLayoutxmlns: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=".SpinnerActivity">

<TextView
android:id="@+id/selection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#007380"
android:hint="selected here"
android:textColor="#ff003c"/>

<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

- Ở đây ta đặt Id cho spinner là spinner1 (nhìn dòng lệnh 16).

- Coding SpinnerActivity.java:

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemSelectedListener;
importandroid.widget.ArrayAdapter;
importandroid.widget.Spinner;
importandroid.widget.TextView;

publicclassSpinnerActivity extendsActivity {
//Tạo một mảng dữ liệu giả
String arr[]={ "Hàng điện tử", "Hàng hóa chất", "Hàng gia dụng"};
TextView selection;

@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
selection =(TextView) findViewById(R.id.selection);
//Lấy đối tượng Spinner ra
Spinner spin=(Spinner) findViewById(R.id.spinner1);
//Gán Data source (arr) vào Adapter
ArrayAdapter<String> adapter=newArrayAdapter<String>(this,android.R.layout.simple_spinner_item,arr);
//phải gọi lệnh này để hiển thị danh sách cho Spinner
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
//Thiết lập adapter cho Spinner
spin.setAdapter(adapter);
//thiết lập sự kiện chọn phần tử cho Spinner
spin.setOnItemSelectedListener(newMyProcessEvent());
}

//Class tạo sự kiện
privateclassMyProcessEvent implements
OnItemSelectedListener
{
//Khi có chọn lựa thì vào hàm này
publicvoidonItemSelected(AdapterView<?> arg0,View arg1,intarg2,longarg3) {
//arg2 là phần tử được chọn trong data source
selection.setText(arr[arg2]);
}
//Nếu không chọn gì cả
publicvoidonNothingSelected(AdapterView<?> arg0) {
selection.setText("");
}
}
}


- Bạn xem Tôi giải thích dưới này:
Hình 2
- android.R.layout.simple_spinner_item dùng để hiển thị phần tử bạn chọn lên spinner. Tương tự như trong ListView bạn có thể custom lại

- Dòng lệnh dưới: android.R.layout.simple_list_item_single_choice để hiện thị danh sách các phần tử trong Spinner khi bạn nhấn vào xem Spinner. Gọi hàm setDropDownViewResource nếu không nó sẽ lỗi chương trình khi bạn nhấn vào xem. Bạn có thể dùng layout khác nhau, chẳng hạn bạn có thể thay thế bằng : android.R.layout.simple_spinner_dropdown_item

Tham khảo: duythanhcse
-----------------------------------------

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------
Xem thêm bài và ví dụ khác:

 

[Tự học lập trình Android] Bài 11: Tìm hiểu về ListView

Tìm hiểu về ListView trong Android

ListView là control được sử dụng khá phổ biến trong các ứng dụng Android, có nhiều cách sử lý khác nhau. Trong bài này chúng ta sẽ tìm hiều 5 cách xử lý ListView hay sử dụng nhất được chia thành 5 trường hợp qua các ví dụ cụ thể

1) Trường hợp 1: Sử dụng ListView control với mảng dữ liệu định sẵn.

Ví dụ: hiển thị mảng dữ liệu lên trên ListView:
Hình 1

- Giao diện trên có 2 control:
+ListView : dùng để hiển thị mảng dữ liệu
+TextView có màu xanh lục: Dùng để hể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 tên là : Vidu_ListView_HardCode_Array, chọn layout phù hợp và kéo thả các control vào giao diện:
Hình 2

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

<LinearLayoutxmlns: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 (nhìn dòng lệnh 15 ở trên), bạn có thể định dạng thêm một số đặc tính khác nhưng trong bài tập này thì chưa cần thiết, chỉ cần hiển thị được dữ liệu lên giao diện là đã đạt yêu cầu.

- Bây giờ bạn mở MainActivity.java lên để viết code:

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;

publicclassMainActivity extendsActivity {
  protectedvoidonCreate(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)
   finalString 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=newArrayAdapter<String>
  (this, android.R.layout.simple_list_item_1, arr);
  //4. Đưa Data source vào ListView
  lv.setAdapter(adapter);
  finalTextView 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(
  newAdapterView.OnItemClickListener() {
    publicvoidonItemClick(AdapterView<?> arg0,
      View arg1,
       intarg2,
       longarg3) {
         //đối số arg2 là vị trí phần tử trong Data Source (arr)
         txt.setText("position :"+arg2+" ; value ="+arr[arg2]);
    }
  });
 }
}


- Dòng lệnh 21.
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arr);
- Dữ liệu từ Data source (arr) sẽ được gắn vào ArrayAdapter, ArrayAdapter sẽ gắn vào ListView.
- Bạn nhìn vào đố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 : android tô màu xanh, đây chính là layout Listview mà được Android xây dựng sẵn, các bài tập kế tiếp ta sẽ tự xây dựng mà không sử dụng cái có sẵn này. Như vậy thì simple_list_item_1 lưu ở đâu? và bên trong nó như thế nào?. Nó được lưu trong SDK/platforms/android-api (x)/data/res/layout/simple_list_item_1.xml. Bạn có thể xem nội dung và vị trí của layout này một cách nhanh chóng bằng đè phím Ctrl + click chuột vào dòng lệnh này, bạn sẽ thấy như bên dưới:

Hình 3

- Đối số thứ 3: chính là arr (data source), bạn có thể truyền vào ArrayList.
- Nhìn vào dòng lệnh 27 chỗ gán sự kiện cho ListView (bạn nhớ là chỉ cần gõ một vài ký tự đầu rồi nhấn Ctrl+ Space Bar thì các lệnh đằng sau sẽ tự động xuất hiện ra cho bạn):
+ 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. Bạn cũng nhớ là chỗ này không có gõ bằng tay mà chỉ cần nhấn tổ hợp phím Ctrl + 1 chọn add unimplement method là nó tự xuất hiện. Ngoài ra nó còn nhiều sự kiện khác các bạn tự tìm hiểu thêm.


2) Trường hợp 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à tương tự 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.
- Bạn tạo một Android Project tên là: Vidu_ListView_Xml_Array
- Để tạo String – Array trong XML bạn làm như sau:

Bước 1: Bấm chuột phải vào thư mục values của Project/ chọn New/Android XML File:
Hình 4

- 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:
Hình 5
Xem kết quả khi bấm nút Finish và quan sát cho nhận xét:
Hình 6
Chú ý là ta cũng có thể thêm dữ liệu vào tập tin strings.xml.

Bước 3: chọn tab Resource ở hình trên:
Hình 7
- Bước 4: Bấm nút “Add…” ở màn hình trên để thêm String-Array:
Hình 8
Ở màn hình trên bạn chọn String Array rồi nhấn OK:

- 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:
Hình 9
- 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:
Hình 10
-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:
Hình 11
- Xem nội dung XML:

<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<string-arrayname="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>

- Như vậy bạn đã biết cách tao 1 tập tin XML và biết cách tạo String Array cũng như tạo các phần tử nằm bên trong nó, Bây giờ trong Coding ta sẽ dựa vào myarray để đọc toàn bộ dữ liệu từ XML ra. Bạn cũng chú ý là myarray khi bạn tạo ra ở trên thì nó cũng được tạo ra trong gen:
Hình 12
- Như bạn thấy đó, trong coding ta sẽ dựa vào đây để lấy ra: R.array.myarray.

* Mở MainActivity.java lên:

- Giống như trường hợp số 1, dó đó trong trường hợp này ta chỉ viết dòng lệnh đọc dữ liệu từ XML đổ về một Mảng (thay vì trường hợp 1 ta hardcode mấy phần tử khi khai báo mảng), còn các phần khác bạn tự làm giống trường hợp 1:

final String arr[]=getResources().getStringArray(R.array.myarray);

Tức là bạn thay thế dòng lệnh thứ 17 trong trường hợp 1 của MainActivity.java bằng dòng lệnh trên.

Thực thi ứng dụng bạn sẽ được kết quả như hình bên dưới:
Hình 13
- Tôi nghĩ tới đây bạn đã thật sự hiểu trường hợp 2.



3) Trường hợp 3: Sử dụng ArrayList và Listview control:

- 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:
Hình 14

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):

<RelativeLayoutxmlns: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:

importjava.util.ArrayList;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.ArrayAdapter;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ListView;
importandroid.widget.TextView;

publicclassMainActivity extendsActivity {
  EditText txtten;
  TextView txtchon;
  Button btn;
  ListView lv;
  ArrayList<String>arrList=null;
  ArrayAdapter<String> adapter=null;
  @Override
 protectedvoidonCreate(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=newArrayList<String>();
  //2. Gán Data Source (ArrayList object) vào ArrayAdapter
  adapter=newArrayAdapter<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(newView.OnClickListener() {
  publicvoidonClick(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(newAdapterView.OnItemClickListener() {
   publicvoidonItemClick(
     dapterView<?> arg0,View arg1,
     intarg2,longarg3) {
       txtchon.setText("position : "+ arg2+ "; value ="+arrList.get(arg2));
     }
  });

//6. xử lý sự kiện Long click
  lv.setOnItemLongClickListener(newAdapterView.OnItemLongClickListener() {
 @Override
 publicbooleanonItemLongClick(AdapterView<?> arg0, View arg1, intarg2, longarg3) {
  arrList.remove(arg2);//xóa phần tử thứ arg2
  adapter.notifyDataSetChanged();
  returnfalse;
  }
 });
 }
}


Giải thích coding:
ArrayList bạn đã được học trong môn Java 1 rồi. Ở đây 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.

4) Trường hợp 4: Sử dụng ArrayList và ListView nhưng từng phần tử trong ArrayList là các Object bất kỳ

Ví dụ: xây dựng ứng dụng hiển thị danh sách nhân viên theo mô hình sau:
Hình 15
- 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:
Hình 16
-Tạo một Android Project tên: Vidu_ListView_ArrayList_Object, cấu trúc như bên dưới:
Hình 17
- Layout XML (activity_main.xml):

<LinearLayoutxmlns: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>


- Xem nội dung từng class:
+ Abstract class Employee:

publicabstractclassEmployee {
privateString id;
privateString name;
publicString getId() {
  returnid;
}

publicvoidsetId(String id) {
  this.id = id;
}

publicString getName() {
 returnname;
}

publicvoidsetName(String name) {
 this.name = name;
}

publicabstractdoubleTinhLuong();
@Override
 publicString toString() {
 // TODO Auto-generated method stub
 returnthis.id+" - "+this.name;
 }
}


+ class EmployeeFullTime:

publicclassEmployeeFullTime extendsEmployee {

@Override
publicdoubleTinhLuong() {
 return500;
}

@Override
publicString toString() {
// TODO Auto-generated method stub
returnsuper.toString() +" -->FullTime="+TinhLuong();
}
}

+ Class EmployeePartTime:

publicclassEmployeePartTime extendsEmployee {

@Override
publicdoubleTinhLuong() {
// TODO Auto-generated method stub
return150;
}

@Override
publicString toString() {
// TODO Auto-generated method stub
returnsuper.toString() +" -->PartTime="+TinhLuong();
}
}


- Bạn thấy là 2 class dẫn xuất từ Employee Tôi làm đơn giản là cách tính lương khác nhau. Đối với FullTime thì lương 500, Partime lương 150. và hàm Xuất toString() cũng khác nhau 1 xí.

- Ở đâ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.

- Xem class MainActivity.java:

importjava.util.ArrayList;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.ArrayAdapter;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ListView;
importandroid.widget.RadioGroup;

publicclassMainActivity extendsActivity {
EditText editId,editName;
Button btnNhap;
RadioGroup radgroup;
ListView lvNhanvien;
ArrayList<Employee>arrEmployee=newArrayList<Employee>();
ArrayAdapter<Employee>adapter=null;
//Khai báo 1 employee object
Employee employee=null;
@Override
protectedvoidonCreate(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=newArrayAdapter<Employee>(this,
android.R.layout.simple_list_item_1,
arrEmployee);
//đưa adapter vào ListView
lvNhanvien.setAdapter(adapter);
btnNhap.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View arg0) {
// TODO Auto-generated method stub
processNhap();
}
});
}

//Xử lý sự kiện nhập
publicvoidprocessNhap()
{
//Lấy ra đúng id của Radio Button được checked
intradId=radgroup.getCheckedRadioButtonId();
String id=editId.getText()+"";
String name=editName.getText()+"";
if(radId==R.id.radChinhthuc)
{
//tạo instance là FullTime
employee=newEmployeeFullTime();
}
else
{
//Tạo instance là Partime
employee=newEmployeePartTime();
}
//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();
}
}


- Chương trình sẽ tự động hiển thị đúng loại Employee mà ta chọn lựa trên giao diện, ở đây bạn lại được ôn tập thêm về tính đa hình trong java. Ứng với mỗi loại Employee nó sẽ tự động gọi hàm toString của loại đó.

Ví dụ: Nếu Employee đó là FullTime thì nó gọi toString của FullTime và ngược lại với PartTime cũng vậy nó sẽ lấy toString của PartTime.

5)Trường hợp 5: Sử dụng ListView nhưng dưới dạng ListActivity
- Thay vì kế thừa từ Activity, ta sẽ cho kế thừa từ ListActivity.
- Và dĩ nhiên cách đặt Id cho ListView cũng có sự khác biệt.
- Bạn xem giao diện bên dưới:
Hình 18

- Xem cách làm XML layout (activity_main.xml):

<LinearLayoutxmlns: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>


- Bạn nhìn vào dòng lệnh thứ 18:

android:id=”@android:id/list“, bạn viết y xì như thế này. Bởi vì nó là id được định nghĩa sẵn bên trong Android.

- Tiếp tục nhìn vào dòng lệnh 24:

android:id=”@android:id/empty“ , cũng là có sẵn của Android. Nó có tác dụng tự động thông báo khi ListView của bạn không có bất kỳ một phần tử nào cả.

- Xem class MainActivity.java:

importandroid.os.Bundle;
importandroid.app.ListActivity;
importandroid.view.View;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;

publicclassMainActivity extendsListActivity {
TextView selection;
String arr[]={"Intel","SamSung",
"Nokia","Simen","AMD",
"KIC","ECD"};
ArrayAdapter<String >adapter=null;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Thiết lập Data Source cho Adapter
adapter=newArrayAdapter<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

protectedvoidonListItemClick(ListView l, View v, intposition, longid) {
// 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: bạn thấy đấy, Tôi cho kế thừa từ ListActivity chứ không phảiActivity. (Android đã viết class ListActivity kế thừa từ Activity rồi). Tức là ListActivity cũng chính là Activity.

- Bạn nhìn vào dòng lệnh số 28:

setListAdapter(adapter);

Ở đây ta hoàn toàn không “Lôi” control ListView ra. Mà ta chỉ cần gọi hàm setListAdapter thì ListView cũng tự động cập nhập dữ liệu. Bạn phải làm chính xác 2 nơi thì mới được như vậy:

1. Kết thừa từ ListActivity,

2. đặt id cho ListView theo đúng quy tắc android:id=”@android:id/list”

Tham khảo: duythanhcse

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------
Xem thêm bài và ví dụ khác:

 

[Tự học lập trình Android] Bài 10: Sử dụng Checkbox và RadioButton trong Android

Sử dụng Checkbox và RadioButton trong Android

- CheckBox và RadioButton đều sử dụng chung 2 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, còn gọi setChecked(false) thì control sẽ bị unchecked.
+ isChecked: kiểm tra xem control có được checked hay không. Nếu có checked thì trả về true ngược lại trả về false
- Checkbox cho phép ta checked nhiều đối tượng, còn RadioButton thì tại một thời điểm nó chỉ cho ta checked 1 đối tượng trong cùng một group mà thôi.
- Nếu bạn muốn người sử dụng có thể chọn nhiều lựa chọn thì bạn nên sử dụng Checkbox, ví dụ xem hình bên dưới:
Hình 1
- Ta có thể thiết lập cho Checkbox bất kỳ được checked mặc định trong XML:
Hình 2

-Trong coding để kiểm tra xem Checkbox đó có được checked hay không thì làm như sau:
Hình 3
- Nếu bạn muốn người sử dụng chỉ được chọn 1 lựa chọn trong nhiều chọn lựa bạn đưa ra thì nên sử dụng RadioButton, ví dụ xem hình bên dưới:
Hình 4

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

- Nhìn vào hình trên bạn thấy là ta phải sử dụng RadioGroup để gom nhóm các RadioButton 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. Trong một màn hình ta có thể tạo nhiều nhóm RadioGroup khác nhau.
- Có 2 cách xử lý RadionButton nào được checked như sau:
Cách 1: Dựa vào RadioGroup để 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ý đúng nghiệp vụ:
Hình 6
- Như hình trên, bạn thấy hàm getCheckedRadioButtonId() : 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 checked lựa chọn nào.
Cách 2: Kiểm tra trực tiếp RadioButton đó có được checked hay không?
Hình 7

Cả 2 cách trên đều có cùng chung một mục đích chỉ là kỹ thuật xử lý khác nhau, tương tự để xóa bỏ checked trong group, ta dùng lệnh:

group.clearChecked();

với group là đối tượng RadioGroup.

Ví dụ: Nhập thông tin cá nhân sử dụng kết hợp giữa RadioButton và CheckBox
Hình 8

Mô tả:
- 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):
Hình 9
- Bạn xem Outline của MainActivity để dễ thiết kế:
Hình 10
Bạn xem coding trong MainActivity:

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 stub
       doShowInformation();
     }
   });
 }

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;
 }
}

Tham khảo: duythanhcse


*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]

-----------------------------------------
Xem thêm bài và ví dụ khác:

 

[Tự học lập trình Android ] Bài 9: Sử dụng TextView, EditText và Button trong Android

Sử dụng TextView, EditText và Button trong Android
- TextView, EditText, Button là 3 control cơ bản nhất của Android. Trong các ví dụ trước bạn đã được làm quen với 3 control này. Trang các ví dụ này chúng ta sẽ cũng cố lại các kiến thức đã học và bổ sung thêm các thuộc tính mới.

1) TextView

- Chỉ cho phép hiển thị thông tin mà không cho phép người dùng chỉnh sửa thì nên sử dụng control này.
- TextView giống như JLabel bên Java, và như Label bên C#
- Một số thuộc tính của TextView mà chúng ta thường xuyên sử dụng nhất:
    Hình 1

- Ta nên thiết lập id cho control để quản lý.
- layout_width, layout_height nên thiết lập cho Textview
- Để thay đổi màu nền dùng background, thay đổi màu chữ dùng textColor, …
- 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:
TextView txt1= (TextView) findViewById(R.id.textView1);
- Mọi control đều kế thừa từ View, và hàm findViewById cũng trả về 1 View theo đúng Id truyền vào, đó là lý do ta ép kiểu về cho đúng với TextView (cách làm nhanh: ngay dòng lệnh này nhấn tổ hợp phím Ctrl +1 là nó sẽ tự ép kiểu nhanh cho bạn)
- Để hiển thị thông tin lên control TextView ta dùng lệnh dưới đây:
txt1.setText(“ Hello world! ”);
- Đẩy lấy thông tin bên trong control TextView ta dùng lệnh dưới đây:
String msg=txt1.getText().toString();

2) EditText
- Control này kế thừa từ TextView và cho phép chỉnh sửa dữ liệu (dĩ nhiên bạn có thể không cho chỉnh sửa dữ liệu bằng coding hay trong xml)
- Để sử dụng EditText rất đơn giản, bạn chỉ việc kéo thả control này vào giao diện và tiến hành thiết lập một số thuộc tính, hoặc viết code trong file layout:
Hình 2

- Như hình bên trên thì bạn chỉ cần kéo loại EditText mà bạn cần (vùng số 1) rồi thả vào giao diện (vùng số 2)
- Một số thuộc tính của EditText:

Hình 3

- Tương tự như TextView bạn cần thiết lập Id, các layout_width, layout_height
- 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.
- textSize để thiết lập kích cỡ font chữ cho EditText
- Trong inputType bạn thấy Tôi kết hợp nhiều giá trị lại với nhau bằng cách dùng toán tử “ | ”, tức là EditText này sẽ có đầy đủ các đặc tính ở bên vế phải mà ta truyền vào, ví dụ:
+ textAutoCorrect : Tự động sửa đúng chính tả, giả sử bạn nhập “teh” thì nó sẽ tự động sửa thành “the”
+ …

- Ta cũng có thể dùng cửa sổ Properties để thiết lập thuộc tính cho dễ dàng hơn (click chuột vào EditText muốn đổi thuộc tính):
Hình 4

- Màn hình trên cho phép ta thay đổi thuộc tính của control một cách dễ dàng.
- Tương tự như TextView, ta cũng phải lấy được control thông qua Id, thao tác với dữ liệu bên trong EditText:
+ Lấy control theo Id:
EditText txtbox=(EditText) findViewById(R.id.editText1);
+ Thiết lập giá trị cho EditText
txtBox.setText(“nhập bất cứ cái gì vào đây xem sao”)
+ Lấy dữ liệu bên trong EditText:
String msg=txtBox.getText().toString()

3) Button
- Dùng để thiết lập sự kiện khi người dùng chọn lựa.
- Cũng kế thừa từ TextView
- Có 2 sự kiện mà người sử dụng thường xuyên thao tác:

Hình 5


Ví dụ: Xây dựng ứng dụng tính cộng trừ nhân chia, giao diện như bên dưới (nhấn nút nào thì thực hiện phép toán cho nút đó):

Hình 6

- Bạn xem Layout để dễ thiết kế:

Hình 7

- Coding mẫu:

import android.os.Bundle;
import android.app.Activity;
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 {
  Button btncong,btntru,btnnhan,btnchia;
  EditText editsoa,editsob;
  TextView txtkq;
  OnClickListener myclick=new OnClickListener() {
  @Override

  public void onClick(View arg0) {
   switch(arg0.getId())
   {
       case R.id.btncong:
          String sa=editsoa.getText()+"";
          String sb=editsob.getText().toString();
          int a=Integer.parseInt(sa);
          int b=Integer.parseInt(sb);
          txtkq.setText(a+ "+" +b + "= " +(a+b));
          break;
       case R.id.btntru:

          String sa=editsoa.getText()+"";
          String sb=editsob.getText().toString();
          int a=Integer.parseInt(sa);
          int b=Integer.parseInt(sb);
          txtkq.setText(a+"-"+b + "="+(a-b));

          break;

    case R.id.btnnhan:
          String sa=editsoa.getText()+"";
          String sb=editsob.getText().toString();
          int a=Integer.parseInt(sa);
          int b=Integer.parseInt(sb);
          txtkq.setText(a+"*"+b + "="+(a*b));           

          break;

    case R.id.btnchia:
         String sa=editsoa.getText()+"";
          String sb=editsob.getText().toString();
          int a=Integer.parseInt(sa);
          int b=Integer.parseInt(sb);
          txtkq.setText(a+"*"+b + "="+(a*b)); 

          break;
    }
  }
};

@Override

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   btncong=(Button) findViewById(R.id.btncong);
   btntru=(Button) findViewById(R.id.btntru);
   btnnhan=(Button) findViewById(R.id.btnnhan);
   btnchia=(Button) findViewById(R.id.btnchia);
   editsoa=(EditText) findViewById(R.id.editsoa);
   editsob=(EditText) findViewById(R.id.editsob);
   txtkq=(TextView) findViewById(R.id.txtketqua);
   btncong.setOnClickListener(myclick);
   btntru.setOnClickListener(myclick);
   btnnhan.setOnClickListener(myclick);
   btnchia.setOnClickListener(myclick);
  }
}


 Tham khảo: duythanhcse

*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]


-----------------------------------------

Tìm kiếm nội dung khác: