Thêm Xóa Sửa các item trong ListView

Ở 2 bài hôm trước Sử dụng ListView chúng ta đã tạo một ứng dụng hiện thị danh sách các sản phẩm lên ListView.
Hôm này chúng ta thực hiện các thao tác thêm, sửa, xóa các sản phẩm trên ListView.



Khi chúng ta click vào 1 item nó sẽ chuyển đến màng hình thứ 2 cho phép chúng ta xem hay sửa thông tin sản phẩm đó

Layout cho màng hình 2

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"> 
        <TextView 
            android:layout_width="100dp" 
            android:layout_height="wrap_content" 
            android:text="Product name" 
            android:textSize="20sp" /> 
        <EditText android:id="@+id/txtProductName" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content" 
            android:ems="10" 
            android:inputType="text" 
            android:textSize="20sp"> 
            <requestFocus /> 
        </EditText> 
    </LinearLayout> 
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"> 
        <TextView 
            android:layout_width="100dp" 
            android:layout_height="wrap_content" 
            android:text="Unit" 
            android:textSize="20sp" /> 
        <EditText 
            android:id="@+id/txtUnit" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content" 
            android:inputType="text" 
            android:textSize="20sp"/> 
    </LinearLayout> 
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"> 
        <TextView 
            android:layout_width="100dp" 
            android:layout_height="wrap_content" 
            android:text="Price" 
            android:textSize="20sp" /> 
        <EditText 
            android:id="@+id/txtPrice" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content" 
            android:inputType="text|numberDecimal" 
            android:textSize="20sp"/> 
    </LinearLayout> 
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center"> 
        <Button android:id="@+id/btnOK" 
            android:layout_width="100dp" 
            android:layout_height="wrap_content" 
            android:textSize="20sp" 
            android:text="OK"/> 
        <Button android:id="@+id/btnCancel" 
            android:layout_width="100dp" 
            android:layout_height="wrap_content" 
            android:textSize="20sp" 
            android:text="Cancel"/> 
    </LinearLayout> 
</LinearLayout>

Class xử lý trên màng hình 2

ProductActivity.java
ProductActivity.java

package com.androidtmc.sales; 
 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
 
import com.androidtmc.sales.models.Product; 
import com.androidtmc.sales.models.SaleManager; 
 
import java.text.DecimalFormat; 
 
/** 
 * Created by minhc_000 on 13/08/2015. 
 */ 
public class ProductActivity extends Activity { 
    public final static String EXTRA_POSITION = "position"; 
    EditText txtProductName,txtUnit,txtPrice; 
    Product product; 
    int position; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_product); 
        //lấy các control trên layout 
        txtProductName = (EditText)findViewById(R.id.txtProductName); 
        txtUnit = (EditText)findViewById(R.id.txtUnit); 
        txtPrice = (EditText)findViewById(R.id.txtPrice); 
        //hiển thị lên màng hình 
        Intent it = getIntent(); 
        position = it.getExtras().getInt(EXTRA_POSITION); 
        product = (Product) SaleManager.get().getProducts().get(position); 
        txtProductName.setText(product.getProductName()); 
        txtUnit.setText(product.getUnit()); 
        String s = (new DecimalFormat("#,###.##")).format(product.getPrice()); 
        txtPrice.setText(s); 
        //thiết đặt sự kiện khi click vào các button 
        Button btnOK = (Button)findViewById(R.id.btnOK); 
        Button btnCancel = (Button)findViewById(R.id.btnCancel); 
        btnOK.setOnClickListener(new OKClickListener()); 
        btnCancel.setOnClickListener(new CancelClickListener()); 
    } 
 
    class OKClickListener implements View.OnClickListener 
    { 
        @Override 
        public void onClick(View v) { 
            //lấy dữ liệu từ layout để cập nhật lại các sản phẩm trong mảng 
            product.setProductName(txtProductName.getText().toString()); 
            product.setUnit(txtUnit.getText().toString()); 
            String s = txtPrice.getText().toString(); 
            s = s.replace(",", ""); 
            double price = Double.parseDouble(s); 
            product.setPrice(price); 
            Intent returnIntent = new Intent(); 
            setResult(Activity.RESULT_OK, returnIntent); 
            finish(); 
        } 
    } 
    class CancelClickListener implements View.OnClickListener 
    { 
        @Override 
        public void onClick(View v) { 
            // không làm gì cả và trở về màng hình trước 
            Intent returnIntent = new Intent(); 
            setResult(Activity.RESULT_CANCELED, returnIntent); 
            finish(); 
        } 
    } 
} 

Tới đây chúng ta có thể build app và thử sửa thông tin của các sản phẩm trong Listview

Thêm button Add trên Actionbar


Để làm được điều này ta chỉnh sửa ở file menu_main.xml


menu_main.xml
menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context=".MainActivity"> 
    <item 
        android:id="@+id/btnAdd" 
        android:orderInCategory="100" 
        android:title="Thêm" 
        android:icon="@android:drawable/ic_menu_add" 
        app:showAsAction="always|withText" /> 
</menu> 

Để sử dụng ta Override lại hàm onOptionsItemSelected(MenuItem item) trong class MainActivity
MainActivity.java
MainActivity.java
@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        int id = item.getItemId(); 
        // nếu btnAdd được click 
        if (id == R.id.btnAdd) { 
            //đến màng hình ProductActivity 
            Intent intent = new Intent(this, ProductActivity.class); 
            //tham số -1 tức ta không truyền 1 position của item nào cả 
            //ta mở ProductActivity để thêm sp mới 
            intent.putExtra(ProductActivity.EXTRA_POSITION, -1); 
            startActivityForResult(intent, 0); 
            return true; 
        } 
        return super.onOptionsItemSelected(item); 
    }
 Tiếp theo ta chỉnh trong hàm onCreate và class OKClickListener trong Class ProductActivity.

Xóa 1 item trong Listview 

Khi chúng ta nhấn giữ lâu sẽ xuât hiện một hộp thoại thông báo xác nhận chúng ta có xóa sản phẩm này không.
+ Sự kiện nhấn giữ lâu 1 item trong Listview. Ta thêm dòng này trong OnCreate của class MainActivity
lv.setOnItemLongClickListener(new ItemLongClickRemove());
Class ItemLongClickRemove ta sẽ định nghĩa sau.
+ Để xuất hiện hộp thoại trên ta dùng đối tượng AlertDialog.Builder
+ Ta tạo thêm classItemLongClickRemove trong class MainActivity
MainActivity.java
MainActivity.java
private class ItemLongClickRemove implements AdapterView.OnItemLongClickListener { 
        @Override 
        public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) { 
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this); 
            alertDialogBuilder.setMessage("Bán có muốn xóa sản phẩm này!"); 
            alertDialogBuilder.setPositiveButton("Có", new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                    // xóa sp đang nhấn giữ 
                    SaleManager.get().getProducts().remove(position); 
                    //cập nhật lại listview 
                    adapter.notifyDataSetChanged(); 
 
                } 
            }); 
            alertDialogBuilder.setNegativeButton("Không", new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                    //không làm gì 
                } 
            }); 
            alertDialogBuilder.show(); 
            return true; 
        } 
    }

Đến đây ứng dụng đã hoàn thành!
Source code
Bài tiếp theo: Sử dụng SQLite tạo Database lưu trữ trong Android
---


----

SHARE

GivesTech

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

4 nhận xét:

  1. chào ad... em có vấn đề muốn hỏi. Em đang làm 1 ứng dụng liên quan đến listview có CSDL. Em muốn xóa một item trong listview nhưng đồng thời cũng xóa trong CSDL thì làm sao ạ??? Thanks ạ!

    Trả lờiXóa
    Trả lời
    1. bạn có thể liên hệ facebook hay skype của mình để biết thêm.
      Facebook: fb.com/cuongloveit
      Skype: cuongloveit

      Xóa
  2. cho em hỏi em muốn xoá toàn bộ listview thì dùng lệnh gì ạ

    Trả lờiXóa
  3. Cho em hỏi có cách nào để tạo chức năng sửa trên textview không ạ do cái textview là cái mà em đã show trên màn hình đó ạ


    Trả lờiXóa