Main Menu

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


 


 







 
 
 
 
 
 

 

Không có nhận xét nào:

Đăng nhận xét