Main Menu

Thứ Năm, 29 tháng 9, 2016

Hướng Dẫn Làm Ứng Dụng Shopping Cart Từ Đầu by Semy Colon


Hướng Dẫn Làm Ứng Dụng Shopping Cart Từ Đầu by Semy Colon

SESSION 3: ADVANCED CONTROLS

SESSION 3: ADVANCED CONTROLS

I. SELECTION LIST CONTROLS 

1. NumbericUpDown Control

Ví dụ :

namespace demo_module3_REVIEW
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            NumericUpDown num = new NumericUpDown();
            num.Maximum = 100;
            num.Minimum = 0;
            num.UpButton();// phương thuc này để tăng giá trị lên 1
            num.DownButton();// phương thuc này để giảm giá trị xuống 1
            num.Increment = 2; // mỗi lần click sẽ tăng lên 2
            // gan1 control nay2 len Form
            this.Controls.Add(num);
        }
    }
}

2. DomainUpDown Control 
* Cho phép lựa chọn giá trị dạng text từ phạm vi các giá trị :
Ví dụ :
* Các thuộc tính của control này là :
+ Items : Thêm các Item lên control này 
   Ví dụ :
       // Gán các Items lên domainUpDown
           
            domainUpDown1.Items.Add("Tháng 5");
            domainUpDown1.Items.Add("Tháng 4");
            domainUpDown1.Items.Add("Tháng 3");
            domainUpDown1.Items.Add("Tháng 2");
            domainUpDown1.Items.Add("Tháng 1");

+ MaximumSize : Xác định kích thước tối đa của Control này
+ MinimumSize : Kích thước tối thiểu của control
+ Read Only : Chỉ được phép đọc
+ SelectedItem : Gía trị mà người dùng chọn trong control
* Các phương thức : UpButton, DownButton;
* Các sự kiện : click, SelectedItemChanged
Ví dụ : 
namespace demo_module3_REVIEW
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Gán các Items lên domainUpDown
           
            domainUpDown1.Items.Add("Tháng 5");
            domainUpDown1.Items.Add("Tháng 4");
            domainUpDown1.Items.Add("Tháng 3");
            domainUpDown1.Items.Add("Tháng 2");
            domainUpDown1.Items.Add("Tháng 1");
            // lựa chọn vị trí xuất hiện của Item đầu tiên
            domainUpDown1.SelectedIndex = 4;
           
        }
    }
}

Sau khi Run ứng dụng :
II . ListView and TreeView Controls
1.  ListView Control 



* Control này dùng để hiển thị các Items dưới dạng List
   Control này giống như các Views icon trên cửa sổ Windows Explorer.
* Cách hiển thị của các View này có 5 cách như sau :
+ Title;
+ List;
+ SmallIcon;
+ LargeIcon
+ Details
* Các thuộc tính
+ Columns => hiển thị tiêu đề cột
+ Items => Truy xuất đến 1 tập các Items ở trong control;
+ Multiselect => Cho phép lựa chọn nhiều Item trong control
+ SelectedItems => Truy xuất đến item được chọn trong control
+ View => Xác định control hiển thị theo dạng nào
* Các phương thức như : 
+ ArrangeIcons : Xắp xếp icon trong control khi hiển thị
+ Clear  : Xóa bỏ Item;
+ GetItemAt : Truy xuất đến Item ở trong ListView ở vị trí nào đó
+ Sort : Xắp xếp List Item;
* Các sự kiện :
+ Column click : Xảy ra khi tiêu đề cột trong ListView được click
+ ItemCheck : Xảy ra khi check trạng thái của Item;
+ ItemSelectionChanged: Xảy ra khi lựa chọn 1 item thì trạng thái bị thay đổi
+ SelectedIndexChanged: Xảy ra khi vị trí của item bị thay đổi
* Demo :
+  Bước 1: Tại giao diện Windows Form : kéo vào 1 ListView như sau:
 + Bước 2: Viết code :
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // tạo danh sách hình ảnh
            ImageList listImage = new ImageList();
            // tạo các đối tượng hình ảnh
            Image img1 = Image.FromFile("images\\19_XUER.jpg");
            Image img2 = Image.FromFile("images\\241906_large.jpg");
            Image img3 = Image.FromFile("images\\20151022110849-8.jpg");
            Image img4 = Image.FromFile("images\\glass_eyes3.jpg");
            Image img5 = Image.FromFile("images\\huyen-my-elly-tran-quyen-ru-voi-dam-cong-chua-1-phunutoday_vn.jpg");
            Image img6 = Image.FromFile("images\\khong-roi-mat-truoc-nhan-sac-cua-a-hau-thuy-van1.jpg");
            Image img7 = Image.FromFile("images\\maxresdefault.jpg");
            Image img8 = Image.FromFile("images\\TV-000010.jpg");
            // thêm các dối tượng image vào ListImage
            listImage.Images.Add(img1);
            listImage.Images.Add(img2);
            // hiển thị listImage trên ListView
            listView1.LargeImageList = listImage;
            // khởi tạo ListViewItem
            ListViewItem listItem1 = new ListViewItem();
            listItem1.Text = "Game ";// đặt tên cho item
            listItem1.ImageIndex = 0;// đạt index cho item
            ListViewItem listItem2 = new ListViewItem();
            listItem2.Text = "Android";
            listItem2.ImageIndex = 1;
            // them các item vào listView
            listView1.Items.Add(listItem1);
            listView1.Items.Add(listItem2);
            // xax1 định cách hiển thị của listView
            listView1.View = View.LargeIcon;

        }
    }

* Sau khi run ứng dụng sẽ như sau :
2. TreeView Control
ví dụ :
* TreeView có 3 kiểu node : 
+ Root
+ Parent
+ Leaf
* TreeView có các thuộc tính sau :
+ Node : truy xuất đến 1 tập các đối tượng TreeNode được biểu diễn trong node gốc.
+ SelectedNode : Lấy giá trị của 1 node đang hiển thị trong TreeView.
+ ShowPlusMinus: Hiển thị dấu (+) và (-) trên TreeNode.
+ ShowRootLines : Hiển thị đường line từ node gốc đến từng node
* Các phương thức :  
+CollapseAll: thu toàn bộ cây
+ ExpandAll : Bung toàn bộ cây
+ GetNodeAt: Truy xuất đến node ở vị trí nào đó.
+ GetNodeCount : Lấy số lượng node ở trên cây .
* Các Event :
+ AfterCollapse : Xảy ra khi node thu hồi lại
+ AfterExpand : Xảy ra khi node bung ra.
+ AfterSelect : Xảy ra khi 1 node được chọn
+ ItemDrag: Xảy ra khi thả 1 Item vào 1 cây
+ NodeMouseClick : Xảy ra khi click vào 1 node.
* Demo
+ Bước 1 : Tại giao diện kéo vào 1 TreeView như sau 

+ Bước 2 ; Viết code :
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // khởi tạo node gốc
            TreeNode nodeRoot = new TreeNode();
            nodeRoot.Text = "Root";
            // thêm 1 node leaf vào nodeRoot
            nodeRoot.Nodes.Add(new TreeNode("Leaf 1"));
            // thêm các node parent và node leaf vào
            TreeNode node1 = new TreeNode("Parent 1");
            TreeNode node2 = new TreeNode("Parent 2");
            TreeNode node3 = new TreeNode("Leaf 2");
            TreeNode node4 = new TreeNode("Leaf 3");
            nodeRoot.Nodes.Add(node1);
            node1.Nodes.Add(node2);
            node1.Nodes.Add(node4);
            node2.Nodes.Add(node3);
            // thêm node gốc này vào treeView
            treeView1.Nodes.Add(nodeRoot);
            //

        }
    }
Sau khi run ứng dụng sẽ như sau :

III . RichTextBox Control 
* Được dùng để hiển thị , nhập , và quản lý dữ liệu text. Control này giống như WordPad.
* Các thuộc tính :
+ Font 
+ ScrollBars
+ SelectedText : truy xuất đến đoạn text người dùng chọn.
+ SelectionLength.
+ Text.
+ WordWrap.
* Các phương thức.
+ AppendText : nối chuỗi này với chuỗi khác.
+ Copy.
+ Past.
+ Redo : Quay lại thao tác trước đó.
+ Undo : Đi tới bước tiếp theo.
* "Font" and "FontStyle" classes
+ Class Font nằm trong namespace : "System.Drawing"
+ FontStyle enumeration được dùng để xác định kiểu cho font.
IV Progressbar Control
*Diễn tả trạng thái của ứng dụng
* Các phương thức :
+ Increment.
+ Maximum.
+ Minimum.
+ PerformStep: Chỉ ra vị trí hiện tại của progressbar và tăng giá trị hiện tại của progressbar bằng thuộc tính Step.
+ Xác định giá trị được gọi bởi phương thức performStep().
+ Style : xác định cách progressbar xử lý .
+ Value : xác định vị trí hiện tại của progressbar .
* Demo 
+ Tại trang giao diện kéo vào 1 thanh progressbar :
+ Bước 2. Viết code :
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // xax1 định giá trị tối thiểu và tối đa cho progressbar
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            // xác định giá trị mỗi lần tăng lên
            progressBar1.Step = 2;

        }

        private void button_start_Click(object sender, EventArgs e)
        {
            for(int i=0; i<100; i++)
            {
                Thread.Sleep(500);
                progressBar1.PerformStep();
            }
        }
    }

+ Sau khi run ứng dụng sẽ như sau :

Thứ Tư, 28 tháng 9, 2016

Session 1 - Introduction to ADO.NET

Session 1 - Introduction to ADO.NET

 

1. Tạo cơ sở dữ liệu : quanlysanpham như sau:
 * Tạo lần lượt 2 bảng danh mục và bảng sản phẩm như sau : 

 * Tạo diagram : 

2. Hướng dẫn tạo class kết nối MS SQL SERVER
* Thêm 4 namespace thường sử dụng cho việt kết nối database :
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.Sql;

* Trong class viết code như sau : 


    class ConnectToDB
    {
        private static SqlConnection con = null;
        public static SqlConnection getConnect()
        {
            try
            {
                string strcon = "Data Source=.;Initial Catalog=tenDatabase;Integrated Security=SSPI;";
                con = new SqlConnection(strcon);
                con.Open();// mở kết nối
            }
            catch
            {
                con = null;
            }
            return con;
        }

    } 

* Tại giao diện kéo vào 1 button : kiểm tra kết nối như sau :
 * Tạo sự kiện click cho button này và viết code kiểm tra kết nối tới database như sau  :

* Sau khi run ứng dụng sẽ như sau : 
3. Tạo class DanhMuc.cs 
* copy 4 namespace trong class ConnectToDB qua :
* Tạo các thuộc tính : madm, tendm
* Tạo 2 constructor như sau : 
* Tạo get set cho các thuộc tính : 

* Tạo phương thức bool them(DanhMuc danhMuc) như sau :

  4. Tại Form giao diện chính : kéo menuStrip vào Form và tạo menu như sau  : 
* Thêm các menu : DanhMuc, SanPham.
* Trong menu DanhMuc, thêm 2 menu con : menu thêm, menu Xóa.
* Set thuộc tính IsMdiContainer = true cho Form1.(Thuộc tính này cho phép form chứa các form #)
 5. Tạo Form : ThemDanhMuc như  sau:
 * Tạo sự kiện click trên button Save , sau đó viết code như sau :

 * Double click trên menu thêm của menu DanhMuc , sau đó viết code như sau :

6. Tại class DanhMuc.cs , tạo thêm phương thức xóa như sau :

*  Output của chương trình như sau :


* Kiểm tra database cho kết quả như sau :

7. Tạo Form : Xóa danh mục như sau :
* Tạo sự kiện click trên button xóa , sau đó viết code như sau :
* Tại Form1  : Thêm menu xóa cho menu DanhMuc như sau :
* Duoble click trên menu này sau đó viết code : mở Form xóa danh mục
 * Run ứng dụng cho kết quả như sau : 
* Kiểm tra database kết quả như sau :


8. Tạo Hàm Update  trong class DanhMuc.cs như sau :  

 

Thứ Bảy, 24 tháng 9, 2016

HƯỚNG DẪN LÀM TOOLBAR VÀ MENU TRONG ANDROID

HƯỚNG DẪN LÀM TOOLBAR VÀ MENU TRONG ANDROID

Part 1 .  How to create a custom toolbar 

Part 2. How to add title and icon on a toolbar

Part 3. How to add a Menu on Toolbar

Part 4. How to add a SearchView on Toolbar

 Part 5. How to get a query from SearchView

Part 6. Searchview - query in another activity.

Part 7. SearchView - making searches

 Part 8. Back button - Navigation

 

Thứ Sáu, 23 tháng 9, 2016

Java những điều có thể bạn đã biết: Map/HashMap hoạt động như thế nào

Java những điều có thể bạn đã biết: Map/HashMap hoạt động như thế nào

 

Đây là một câu hỏi thường gặp trong những buổi phỏng vấn ứng viên Java, và cũng có không ít bạn vì câu hỏi này mà gặp trắc trở, hôm nay chúng ta sẽ thảo luận về nó.
Đầu tiên, Map và HashMap là gì?
Map là một tập dữ liệu được lưu dưới dạng key-value. Một Map không thể chứa những key trùng nhau, nhưng mỗi key thì có thể được ánh xạ đến nhiều hơn một giá trị.
Map interface được định nghĩa gồm những method phục vụ những hoạt động cơ bản (như put, get, remove, containsKey, containsValue, size, empty), phục vụ việc thao tác hàng loạt (như putAll, clear), và phục vụ việc xem dữ liệu trong tập (như keySet, entrySet, values).
HashMap là một implement của Map interface trong Java. HashMap không synchronize và không thread safe. Cách implement thì chắc các bạn đã quá rõ rồi, tôi sẽ không cần đưa ra ví dụ nữa.
HashMap hoạt đông dựa trên Hashing. Để hiểu được Hashing , chúng ta phải hiểu được các khái niệm về HashFunction, HashValue và Bucket.
Vậy, Hashing là gì?
Nào, cùng xét một mảng dữ liệu không được sắp xếp, làm sao để tìm kiếm trên mảng đó?
Tất nhiên, để tìm kiếm chúng ta phải thực hiện việc so sánh tất cả các phần tử của mảng. Vậy độ phức tạp sẽ là O(n).
Nếu mảng đó được sắp xếp, áp dụng tìm kiếm nhị phân thì độ phức tạp sẽ giảm xuống còn O(log n).
Ngoài ra, việc tìm kiếm còn có thể nhanh hơn nếu như hàm chỉ trả về một index của phần tử trong mảng. Trong trường hợp này, độ phức tạp chỉ còn là O(1). Đó chính là Hash Function.
Hash function là một hàm mà khi đưa vào một giá trị bất kì, nó sẽ trả về một giá trị tương ứng gọi là Hash Value.
Java cung cấp một hash function đó chính là hashCode(). Hàm này được implement trong class Object và đương nhiên tất cả các class trong Java đều có vì chúng đều thừa kế từ Object.
Như đã nói ở trên, để hiểu về Hashing, chúng ta phải hiểu về HashFunction, HashValue và Bucket. Giờ đã có hai, vậy Bucket là gì?
Bucket là khái niệm dùng để chỉ nơi mà chúng ta lưu trữ những cặp key-value. Trong HashMap, Bucket sử dụng một LinkedList để lưu trữ.
Trong Java HashMap được implement như thế nào?
Trong HashMap, hàm get(Object key) gọi hàm hashCode() của key để lấy hashValue của key, sau đó mang hashValue này để tìm bucket tương ứng, nơi mà key-value đang được lưu như là một Entry object. Ngó qua implement ta thấy như sau.
public V get(Object key) {
  Node<K,V> e;
  return (e = getNode(hash(key), key)) == null ? null : e.value;
}

static final int hash(Object key) {
  int h;
  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
Hàm get(Object key) cũng kiểm tra xem key có null hay không. Null cũng được coi là một key trong HashMap, và dĩ nhiên chỉ có một key null. Nếu key là null thì hash luôn luôn là 0 và tương ứng index cũng là 0. Nếu key không phải là null thì gọi hash function tương ứng với key.
Kế tiếp, hashValue được dùng để tìm bucket tương ứng nơi mà Entry đang được lưu. Entry được lưu trữ trong bucket với hash, key, value và bucket index. Cuối cùng là trả về giá trị tương ứng với key.
Lưu ý nho nhỏ, độ phức tạp của hàm get() và put() trong HashMap là O(1) vì nó sử dụng hashCode để tìm giá trị.
Và bây giờ tôi chắc chắn rằng các bạn đang thắc mắc, hash thì cũng chỉ là một con số, khả năng trùng nhau là có, vậy Làm thế nào nếu nhiều key có cùng một hashValue?
Đây là lý do mà việc implement hàm equals() chung với hashCode() trở nên cực kì quan trọng.
Như đã nói ở trên, một bucket là một LinkedList, nó không phải là java.util.Linkedlist nên các bạn đừng hiểu nhầm. HashMap có implementation riêng cho việc này. Do đó, nếu một hashValue chỉ đến một bucket chứa nhiều Entry nó sẽ duyệt LinkedList và so sánh các key của mỗi Entry bằng cách sử dụng key.equals() cho đến khi equals() trả về true. Sau đó giá trị tương ứng với key sẽ được trả về.
Tất cả các class đều có thể là key nếu nó được override hàm equals() và hashCode(), ngoài ra việc này cũng giúp biến các class trở thành immutable class.
Nói về performance.
Để nói về performance, đối với một HashMap có hai yếu tố sẽ ảnh hưởng trực tiếp tới performance đó là initial capacity (kích thước khởi tạo) và load factor (hệ số tải).
Capacity là con số nói về số lượng bucket trong HashMap.
Load factor là chỉ số để đo đếm việc đến ngưỡng nào đó thì capacity của HashMap sẽ được tự đông tăng lên. Khi số lương entry trong HashMap đạt đến ngưỡng vượt quá load factor cũng như capacity thì HashMap sẽ được rehash. Sau đó HashMap sẽ tăng số lượng bucket lên gấp đôi. Giá trị mặc định của load factor là 0.75.
Hy vọng qua bài viết này các bạn đã hiểu về các hoạt động của HashMap trong Java, và không bị lúng túng trong những lần phỏng vấn bị hỏi về vấn đề này nữa.
Chào tạm biệt và hẹn gặp lại các bạn trong những bài viết tới.

Hướng Dẫn Tích Hợp Intenet Banking Vào Trong Ứng Dụng Android

Hướng Dẫn Tích Hợp Intenet Banking Vào Trong Ứng Dụng Android
Xem chi tiết tại : http://developers.1pay.vn/http-apis
Hướng dẫn đăng ký dịch vụ
Hướng dẫn sử dụng code mẫu

CÁC CÂU HỎI PHỎNG VẤN ANDROID NÂNG CAO

Android Gửi Email sử dụng Parse API with Parse Cloud Code simple example Tutorial

Android sending Ecommerce emails using Parse API with Parse Cloud Code simple example Tutorial

 

xem chi tiết tại : http://www.tutorialsface.com/2015/09/android-sending-ecommerce-emails-using-parse-api-with-parse-cloud-code-simple-example-tutorial/

 

Hướng dẫn làm ShoppingCart Simple Part 2

Hướng dẫn làm ShoppingCart Simple Part 2

Thứ Tư, 21 tháng 9, 2016

HƯỚNG DẪN LÀM SHOPPING CART SIMPLE



HƯỚNG DẪN LÀM SHOPPING CART SIMPLE



Hướng dẫn làm ShoppingCart Simple Part 2


Bước 1 . Tạo Layout 

 *Layout giao diện trang MainActivity : chứa danh mục các sản phẩm như sau :

<
?xml version="1.0" encoding="utf-8"?
> <LinearLayout 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"     android:orientation="vertical"     tools:context="com.example.manngo.shoppingcartsimple.MainActivity">     <TextView         android:layout_gravity="center_horizontal"         android:layout_margin="5dp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/title_page"         android:text="CatalogProduct"         android:textSize="15dp"         />     <ListView         android:id="@+id/list_catalog"         android:background="#ff9100"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:layout_weight="1">     </ListView>     <Button         android:layout_margin="5dp"         android:text="ViewCart"         android:id="@+id/button_view_cart"         android:layout_gravity="right"         android:layout_width="wrap_content"         android:layout_height="wrap_content" /> </LinearLayout>
 
* Layout Trang DetailActivity như sau :
 
 


<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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"     android:orientation="vertical"     tools:context="com.example.manngo.shoppingcartsimple.ProductDetailActivity">     <LinearLayout         android:orientation="horizontal"         android:layout_width="fill_parent"         android:layout_height="wrap_content">         <ImageView             android:layout_margin="5dp"             android:layout_width="120dp"             android:layout_height="120dp"             android:id="@+id/image_product_detail"/>         <LinearLayout             android:orientation="vertical"             android:layout_weight="1"             android:layout_width="fill_parent"             android:layout_height="match_parent">             <TextView                 android:textSize="20dp"                 android:textStyle="bold"                 android:text="Product Title"                 android:id="@+id/text_title_detail"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"/>             <TextView                 android:textSize="20dp"                 android:textStyle="normal"                 android:text="Price"                 android:textColor="#ff0011"                 android:id="@+id/text_price_detail"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"/>             <EditText                 android:id="@+id/edt_quantity_detail"                 android:hint="Enter Quantity"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"/>         </LinearLayout>     </LinearLayout>     <TextView         android:layout_margin="5dp"         android:background="#e6d7a1"         android:layout_weight="1"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Mo ta San Pham"         android:id="@+id/text_discription_detail"/>     <Button         android:layout_gravity="right"         android:text="Add Cart"         android:id="@+id/button_add_cart"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/> </LinearLayout>
* Layout trang giỏ hàng (CartActivity) như sau :






<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context="com.example.manngo.shoppingcartsimple.ShoppingCart2Activity">

    <TextView
        android:textSize="20dp"
        android:id="@+id/text_title_cart"
        android:text="My Cart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <ListView
        android:background="#ff7700"
        android:cacheColorHint="#000dff"
        android:id="@+id/list_cart"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>
    <LinearLayout
        android:padding="5dp"
        android:orientation="horizontal"
        android:id="@+id/LinearLayout01"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:textSize="15dp"
            android:text="Remove from Cart"
            android:layout_gravity="right"
            android:id="@+id/button_remove_from_cart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:textSize="15dp"
            android:text="Proceed to Checkout"
            android:layout_gravity="left"
            android:id="@+id/button_procced_to_checkout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>




 * Layout cho từng item trong ListView , ở đây mỗi item hiển thị cho 1 sản phẩm có dạng như sau :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff6a00"
    android:padding="5dp">
    <ImageView
        android:id="@+id/image_product_row"
        android:layout_width="120dp"
        android:layout_height="120dp" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:textSize="20dp"
            android:textStyle="bold"
            android:text="Title"
            android:id="@+id/text_title_product_row"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:textColor="#ff0004"
            android:text="price"
            android:textSize="20dp"
            android:id="@+id/text_price_product_row"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>


* Tiếp theo chúng ta tạo layout cho từng item trong giỏ hàng có dạng như sau :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f5f5a2"
    android:padding="5dp">
    <ImageView
        android:id="@+id/image_product_cart"
        android:layout_width="120dp"
        android:layout_height="120dp" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/text_title_cart_row"
                android:textSize="20dp"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:text="Title cart"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <CheckBox
                android:background="#001aff"
                android:layout_gravity="left"
                android:id="@+id/checkbox_cart"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:clickable="false" /* chú ý phải thêm 2 thuộc tính này*/
                android:focusable="false"
/>

        </LinearLayout>
        <TextView
            android:textColor="#ff0008"
            android:id="@+id/text_price_cart"
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/text_qty_cart"
            android:text="Quantity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

Bước 2. Tạo Class Product :

public class Product {
    public String title;
    public Drawable productImage;
    public String discription;
    public double price;
    public boolean selected;

    public Product(String title, Drawable productImage, String discription, double price) {
        this.title = title;
        this.productImage = productImage;
        this.discription = discription;
        this.price = price;
    }
}

Bước 3. Tạo class ShoppingCartHelper

Class này giống như Controller chứa các thông tin về danh mục sản phẩm và giỏ hàng
public class ShoppingCartHelper {
    public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
    private static List<Product> listCatalog;
    private static List<Product> listCart;
    // tạo danh mục sản phẩm    public static List<Product> getCatalog(Resources res){
        if (listCatalog == null){
            listCatalog = new Vector<Product>();
            listCatalog.add(new Product("San Pham 1", res.getDrawable(R.drawable.android),"This isSan Pham 1", 31.20));
            listCatalog.add(new Product("San Pham 2", res.getDrawable(R.drawable.android3),"This isSan Pham 2", 31.20));
            listCatalog.add(new Product("San Pham 3", res.getDrawable(R.drawable.android5),"This isSan Pham 3", 31.20));
            listCatalog.add(new Product("San Pham 4", res.getDrawable(R.drawable.glass_eyes2),"This isSan Pham 4", 31.20));
            listCatalog.add(new Product("San Pham 5", res.getDrawable(R.drawable.glass_eyes3),"This isSan Pham 5", 31.20));
            listCatalog.add(new Product("San Pham 6", res.getDrawable(R.drawable.hinh13),"This isSan Pham 6", 31.20));
        }
        return listCatalog;

    }
    // tạo giỏ hàng    public static List<Product> getCart(){
        if (listCart == null){
            listCart = new Vector<Product>();
        }
        return listCart;
    }

}
 
 

Bước 4 :Tạo custom ProductAdapter như sau:

public class ProductAdapter extends BaseAdapter {
    private List<Product> mProductList;
    private LayoutInflater mInflater;
   // private boolean mShowCheckBox;

    public ProductAdapter(List<Product> mProductList, LayoutInflater mInflater) {
        this.mProductList = mProductList;
        this.mInflater = mInflater;
    }

    @Override
    public int getCount() {
        return mProductList.size();
    }

    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }

    @Override
    public long getItemId(int id) {
        return id;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        final ViewItem item;
        if (view == null){
            view = mInflater.inflate(R.layout.row_product, null);
            item = new ViewItem();
            item.productImageView = (ImageView) view.findViewById(R.id.image_product_row);
            item.productTitle = (TextView) view.findViewById(R.id.text_title_product_row);
            item.productPrice = (TextView) view.findViewById(R.id.text_price_product_row);
            view.setTag(item);
        }else {
            item = (ViewItem) view.getTag();
        }
        Product curProduct = mProductList.get(position);
        item.productImageView.setImageDrawable(curProduct.productImage);
        item.productTitle.setText(curProduct.title);
        item.productPrice.setText("Price: "+curProduct.price+"$");

        return view;
    }

    private class ViewItem{
        ImageView productImageView;
        TextView productTitle;
        TextView productPrice;
        CheckBox productCheckbox;
    }
}

Bước 5 : Tại MainActivity viết Code như sau 

public class MainActivity extends AppCompatActivity {
    ListView lvProduct;
    Button btnViewCart;
    private List<Product> mProductList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvProduct = (ListView) findViewById(R.id.list_catalog);
        btnViewCart = (Button) findViewById(R.id.button_view_cart);
        displayProduct();
        displayCart();
    }
    private void displayProduct(){
        // Obtain a reference to the product catalog
        mProductList = ShoppingCartHelper.getCatalog(getResources());
        ProductAdapter adapter = new ProductAdapter(mProductList, getLayoutInflater());
        lvProduct.setAdapter(adapter);
        lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent productDetailIntent = new Intent(getBaseContext(), ProductDetailActivity.class);
                productDetailIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
                startActivity(productDetailIntent);
            }
        });
    }
    private void displayCart(){
        btnViewCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(), ShoppingCart2Activity.class));
            }
        });
    }
}

Bước 6 Tạo ProductDetailActivity viết code như sau :

 public class ProductDetailActivity extends AppCompatActivity {

    ImageView imgHinh;
    TextView txtTitle, txtPrice, txtDiscription;
    EditText edtQty;
    Button btnAddCart;
    Product SelectedProduct;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        init();
        displayDetail();
        addCart();

    }
    private void init(){
        imgHinh = (ImageView) findViewById(R.id.image_product_detail);
        txtTitle = (TextView) findViewById(R.id.text_title_detail);
        txtPrice = (TextView) findViewById(R.id.text_price_detail);
        txtDiscription = (TextView) findViewById(R.id.text_discription_detail);
        edtQty = (EditText) findViewById(R.id.edt_quantity_detail);
        btnAddCart = (Button) findViewById(R.id.button_add_cart);
    }
    private void displayDetail(){
        // Khởi tạo danh sach san pham
        List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());

        // nhận intent truyền qua
        int ProductIndex = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
        // khởi tạo dối tượng sản phẩm
         SelectedProduct = catalog.get(ProductIndex);
        imgHinh.setImageDrawable(SelectedProduct.productImage);
        txtTitle.setText(SelectedProduct.title);
        txtPrice.setText("Price "+SelectedProduct.price+" $");
        txtDiscription.setText("Discription : "+SelectedProduct.discription);
    }
    private void addCart(){
        // Khởi tạo giỏ hàng
        final List<Product> myCart = ShoppingCartHelper.getCart();

        btnAddCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myCart.add(SelectedProduct);
                Toast.makeText(getBaseContext(), "Bạn đã thêm san pham "+SelectedProduct.title+
                        " Vào trong gio hang", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        // Disable the add to cart button if the item is already in the cart
        if (myCart.contains(SelectedProduct)){
            btnAddCart.setEnabled(false);
            btnAddCart.setText("Item in cart");
            Toast.makeText(getBaseContext(), "san pham da co trong gio hang", Toast.LENGTH_SHORT).show();
        }
    }
}


Bước 7 : TẠO CUSTOM CartAdapter

public class CartAdapter extends BaseAdapter {
    private List<Product> mProductList;
    private LayoutInflater mInflater;
    private boolean mShowCheckBox;
    public CartAdapter(List<Product> mProductList, LayoutInflater mInflater, boolean mShowCheckBox) {
        this.mProductList = mProductList;
        this.mInflater = mInflater;
        this.mShowCheckBox = mShowCheckBox;
    }
    @Override
    public int getCount() {
        return mProductList.size();
    }
    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }
    @Override
    public long getItemId(int id) {
        return id;
    }
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        final ViewItem item;
        if (view == null){
            view = mInflater.inflate(R.layout.row_cart, null);
            item = new ViewItem();
            item.productImageView = (ImageView) view.findViewById(R.id.image_product_cart);
            item.productTitle = (TextView) view.findViewById(R.id.text_title_cart_row);
            item.productPrice = (TextView) view.findViewById(R.id.text_price_cart);
            item.productCheckbox = (CheckBox) view.findViewById(R.id.checkbox_cart);
            view.setTag(item);
        }else {
            item = (ViewItem) view.getTag();
        }
        Product curProduct = mProductList.get(position);
        item.productImageView.setImageDrawable(curProduct.productImage);
        item.productTitle.setText(curProduct.title);
        item.productPrice.setText(curProduct.price+"");
//      kiem63 tra neu mShowCheckBox = true thì hiển thị checkBox
        if (!mShowCheckBox){
            item.productCheckbox.setVisibility(View.GONE);
        }else {
            if (curProduct.selected == true){
                item.productCheckbox.setChecked(true);
            }else {
                item.productCheckbox.setChecked(false);
            }
        }
        return view;
    }
    private void disPlayCheckbox(){
    }
    private class ViewItem{
        ImageView productImageView;
        TextView productTitle;
        TextView productPrice;
        CheckBox productCheckbox;
    }
}
BƯỚC 8: Tạo CartActivity 
public class ShoppingCart2Activity extends AppCompatActivity {

    ListView lvCart;
    Button  btnProceedToCheckout;
    private List<Product> mCartList;
    private CartAdapter adapter;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart2);
        init();
        displayCart();
        RemoveProductFromCart();
    }
    private void init(){
       // lvCart = (ListView) findViewById(R.id.list_cart);
        btnProceedToCheckout = (Button) findViewById(R.id.button_procced_to_checkout);
    }
    private void displayCart(){
        mCartList = ShoppingCartHelper.getCart();

        // Make sure to clear the selection
        for(int i=0; i<mCartList.size(); i++) {
            mCartList.get(i).selected = false;
        }

        // Create the list     final ListView listViewCatalog = (ListView) findViewById(R.id.list_cart);
        adapter = new CartAdapter(mCartList, getLayoutInflater(), true);
        listViewCatalog.setAdapter(adapter);

        listViewCatalog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Product selectedProduct = mCartList.get(position);
                if(selectedProduct.selected == true)
                    selectedProduct.selected = false;
                else                    selectedProduct.selected = true;

                adapter.notifyDataSetInvalidated();
            }
        });
    }
    private void RemoveProductFromCart(){
        Button removeButton = (Button) findViewById(R.id.button_remove_from_cart);
        removeButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                // Loop through and remove all the products that are selected 
    // Loop backwards so that the remove works correctly
               for(int i=mCartList.size()-1; i>=0; i--) {

                    if(mCartList.get(i).selected) {
                        mCartList.remove(i);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }
}