intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Hướng dẫn lập trình cơ bản với Android - Bài 3

Chia sẻ: Ha Ngoc Chung | Ngày: | Loại File: PDF | Số trang:13

234
lượt xem
109
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

ViewGroup thông thường chúng ta hay gặp là LinearLayout, Relative Layout. Xây dựng custom ViewGroup cho phép chúng ta tạo 1 tập các widget được sắp xếp theo ý muốn rồi đưa vào sử dụng.

Chủ đề:
Lưu

Nội dung Text: Hướng dẫn lập trình cơ bản với Android - Bài 3

  1. Hư ng d n l p trình cơ b n v i Android - Bài 3 http://diendan.vietandroid.com/cac-bai-hoc-co-kem-ma-nguon/533-huong- Reflink: dan-lap-trinh-co-ban-voi-android-bai-3-a.html List tutorial Bài 0 - Cài ñ t và s d ng Android v i Eclipse Bài 1 - Cơ b n Android Bài 2 - Xây d ng giao di n ñơn gi n Bài 3 - ViewGroup và Custom Adapter Bài 4 - Intent và Broadcast Receiver Bài 5 - Service Bài 6 - SQLite Bài 7 - Content Provider Hi m i ngư i. Tình hình là vietandroid ñang phát tri n r t m nh m , s lư ng newbie tăng lên nhanh chóng => mình quy t ñ nh vi t ti p lo t bài hư ng d n l p trình căn b n ñ giúp ñ các lính m i làm quen v i Android nhanh hơn. Trong bài này mình s hư ng d n cách t o 1 custom ViewGroup, s d ng ViewGroup này vào ListView, và cu i cùng là t o 1 Option Menu. ðây cũng s là bài cu i cùng mình vi t v làm vi c v i View, các bài sau s chuy n qua Intent và BroadCast Receiver. Custom ViewGroup ViewGroup thông thư ng chúng ta hay g p là LinearLayout, Relative Layout. Xây d ng custom ViewGroup cho phép chúng ta t o 1 t p các widget ñư c s p x p theo ý mu n r i ñưa vào s d ng. Yêu c u: Xây d ng ng d ng d ng To Do List: Cho phép nh p vào n i dung công vi c và th i gian th c hi n công vi c r i ñưa vào list công vi c. Cho phép xóa các công vi c kh i list. B1: Kh i t o project: File -> New -> Android Project Project name: Example 3 Build Target: Ch n Android 1.5 Application name: Example 3 Package name: at.exam Create Activity: Example => Kích nút Finish. B2: Xây d ng custom view group trong XML. ði t i res\layout t o 1 file XML m i là list.xml. Gõ n i dung sau vào: Mã:
  2. android:paddingTop="45px" android:paddingRight="10px" /> Custom ViewGroup c a chúng ta ñây khá ñơn gi n, ñó là 1 LinearLayout ch a 2 thành ph n: 1 CheckBox và 1 LinearLayout khác g m 2 TextView ñ hi n th n i dung công vi c và th i gian. B3: ðã xong giao di n cho custom ViewGroup, chúng ta s thi t k giao di n cho chương trình trong main.xml. ñây mình dùng l i giao di n c a Example 2 trong bài 2. Mã:
  3. android:text="@string/hour_edit" android:typeface="normal" android:textSize="15px" android:textStyle="bold" android:padding="5px" /> B4: T o file colors.xml trong res\value: Mã: www.Beenvn.com – T Sách Online
  4. #ffffff #cccccc #cccccc work_color là màu c a n i dung công vi c trong list. time_color màu c a th i gian công vi c. hint_color màu c a text hint (dòng hư ng d n) các EditText. B5: Ch nh s a file strings.xml trong res\value: Mã: Example 3 Enter the work here Hour Minute Add work __________________ B6: Time to coding. ði t i src\at.exam t o m t class m i là CustomViewGroup v i n i dung sau: Mã: package at.exam; import android.content.Context; import android.view.LayoutInflater; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; public class CustomViewGroup extends LinearLayout { public CheckBox cb; public TextView workContent; public TextView timeContent; public CustomViewGroup(Context context) { super(context); //S d ng LayoutInflater ñ gán giao di n trong list.xml cho class này LayoutInflater li = (LayoutInflater) this.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); li.inflate(R.layout.list, this, true); //L y v các View qua Id cb = (CheckBox) findViewById(R.id.check_work); workContent = (TextView) findViewById(R.id.work_content); timeContent = (TextView) findViewById(R.id.time_content); } } ðo n code trên giúp ta ñ nh nghĩa giao di n c a custom ViewGroup m i d a trên file list.xml. M i ngư i cũng có th t o giao di n b ng code, ko c n s d ng XML nhưng s ph c t p hơn và mình www.Beenvn.com – T Sách Online
  5. cũng ko gi i thi u ñây. B7: T o 1 class Work cũng trong at.exam ñ th hi n công vi c: Mã: package at.exam; public class Work { private String workContent; private String timeContent; private boolean isChecked; public Work(String workContent, String timeContent) { this.workContent = workContent; this.timeContent = timeContent; isChecked = false; } public String getContent() { return workContent; } public String getTime() { return timeContent; } public void setChecked(boolean isChecked) { this.isChecked = isChecked; } public boolean isChecked() { return isChecked; } } Code r t ñơn gi n nên mình s không chú thích n a. B8: Chúng ta ñã t o xong custem ViewGroup, bây gi chính là lúc s d ng. T o 1 class m i tên là ListWorkApdapter trong at.exam: Mã: package at.exam; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; public class ListWorkAdapter extends ArrayAdapter{ ArrayList array; int resource; Context context; www.Beenvn.com – T Sách Online
  6. public ListWorkAdapter(Context context, int textViewResourceId, ArrayList objects) { super(context, textViewResourceId, objects); this.context = context; resource = textViewResourceId; array = objects; } //Phương th c xác ñ nh View mà Adapter hi n th , ñây chính là CustomViewGroup //B t bu c ph i Override khi k th a t ArrayAdapter @Override public View getView(int position, View convertView, ViewGroup parent) { View workView = convertView; if (workView == null) { workView = new CustomViewGroup(getContext()); } //L y v ñ i tư ng Work hi n t i final Work work = array.get(position); if (work != null) { TextView workContent = ((CustomViewGroup) workView).workContent; TextView timeContent = ((CustomViewGroup) workView).timeContent; CheckBox checkWork = ((CustomViewGroup) workView).cb; //Set s ki n khi ñánh d u vào checkbox trên list checkWork.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { work.setChecked(isChecked); } }); //L y v n i dung cho TextView và CheckBox d a vào ñ i tư ng Work hi n t i workContent.setText(work.getContent()); timeContent.setText(work.getTime()); checkWork.setChecked(work.isChecked()); } return workView; } } ListWorkAdapter s ñư c s d ng thay th cho ArrayAdapter ñư c bind v i ListView. Thông thư ng ArrayAdapter ch cho hi n th String b ng TextView, nhưng v i vi c k th a và override phương th c getView, ta có th ñ nh nghĩa l i hi n th cho các thành ph n c a ListView. B9: Vi c cu i cùng c n làm là vi t l i Activity. T i Example.java và ch nh s a theo n i dung sau: www.Beenvn.com – T Sách Online
  7. Mã: package at.exam; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; 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; public class Example extends Activity { //Các h ng dùng cho t o Option Menu private static final int DELETE_WORK = Menu.FIRST; private static final int ABOUT = Menu.FIRST + 2; ArrayList array; ListWorkAdapter arrayAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); array = new ArrayList(); arrayAdapter = new ListWorkAdapter(this, R.layout.list, array); final EditText workEnter = (EditText) findViewById(R.id.work_enter); final EditText hourEdit = (EditText) findViewById(R.id.hour_edit); final EditText minuteEdit = (EditText) findViewById(R.id.minute_edit); final Button button = (Button) findViewById(R.id.button); //T o list view cho danh sách công vi c final ListView list = (ListView) findViewById(R.id.list); list.setAdapter(arrayAdapter); OnClickListener add = new OnClickListener() { @Override public void onClick(View v) { if (workEnter.getText().toString().equals("") || hourEdit.getText().toString().equals("") || minuteEdit.getText().toString().equals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(Example.this); builder.setTitle("Info missing"); www.Beenvn.com – T Sách Online
  8. builder.setMessage("Please enter all information of the work"); builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); builder.show(); } else { String workContent = workEnter.getText().toString(); String timeContent = hourEdit.getText().toString() + ":" + minuteEdit.getText().toString(); Work work = new Work(workContent, timeContent); array.add(0, work); arrayAdapter.notifyDataSetChanged(); workEnter.setText(""); hourEdit.setText(""); minuteEdit.setText(""); } } }; button.setOnClickListener(add); } //T o Option Menu public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, DELETE_WORK, 0,"Delete" ).setIcon(android.R.drawable.ic_delete); menu.add(0, ABOUT, 0,"About" ).setIcon(android.R.drawable.ic_menu_info_details); return true; } //X lý s ki n khi các option trong Option Menu ñư c l a ch n public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case DELETE_WORK: { deleteCheckedWork(); break; } case ABOUT: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("VietAndroid"); builder.setMessage("AUTHOR:" + "\n" + " Nguyen Anh Tuan" + "\n" + "SOURCE:" + "\n" + " diendan.vietandroid.com"); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { www.Beenvn.com – T Sách Online
  9. public void onClick(DialogInterface dialog, int which) { } }); builder.setIcon(android.R.drawable.ic_dialog_info); builder.show(); break; } } return true; } private void deleteCheckedWork() { if (array.size() > 0) { for (int i = 0; i < array.size(); i++) { if (i > array.size()) { break; } if (array.get(i).isChecked()) { array.remove(i); arrayAdapter.notifyDataSetChanged(); continue; } } } } } OK. V y là xong. Option Menu là menu n ch hi n ra khi b n nh n nút Menu c a ñi n tho i. Option Menu r t ti n trong vi c ñưa ra các tùy ch nh, gi ng như khi b n nh n phím Esc khi ñang chơi game trên PC v y. Các b n có th lưu ý là thay vì s d ng ArrayList như trư c mình ñã thay b ng ArrayList và trong kh i t o ñ i tư ng arrayAdapter thì ñ i s th 2 là R.layout.list thay vì android.R.layout.simple_list_item_1, nghĩa là chúng ta ñã s d ng layout do mình t t o thay vì layout Android cung c p s n cho hi n th các thành ph n c a ListView. N u ch y th , các b n có th th y khi ta ñánh d u vào checkbox c a 1 thành ph n trong list, r i nh n Menu và ch n delete thì thành ph n s b g b kh i danh sách. www.Beenvn.com – T Sách Online
  10. www.Beenvn.com – T Sách Online
  11. www.Beenvn.com – T Sách Online
  12. www.Beenvn.com – T Sách Online
  13. K t thúc bài 3 www.Beenvn.com – T Sách Online
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2