2016-06-10 93 views
0

我想在列表視圖中設置我的更新的適配器,但我有一個問題是,列表視圖中的舊值仍然存在,並在下面,新值設置,所以我只想在列表視圖中只設置新的刷新值。如何刷新Android Listview只有新值

+0

添加一些相關的代碼,你已經嘗試過,那麼我們將能夠幫助你? –

+0

發表你的代碼請 – earthw0rmjim

+0

它更好地使用RecyclerView .. https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html – fatboy

回答

1

試試這個,

這是例如,對於產品清單包含產品名稱及成本。

我採取ProductDetails實體類包含產品名稱和價格

public class ProductDetails { 
    String productName; 
    int productPrice; 

    public String getProductName() { 
     return productName; 
    } 

    public void setProductName(String productName) { 
     this.productName = productName; 
    } 

    public int getProductPrice() { 
     return productPrice; 
    } 

    public void setProductPrice(int productPrice) { 
     this.productPrice = productPrice; 
    } 
} 
MainActivity.java添加此代碼

 Button updateCostList = (Button)findViewById(R.id.btnUpdateCostList); 
     ListView costList = (ListView)findViewById(R.id.costList); 
     // create instance of custom adapter for custom list view 
     customCostlistAdapter = new CustomCostlistAdapter(); 
     costList.setAdapter(customCostlistAdapter); 

     // when we user click on update list details 
     updateCostList.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // we have set adapter properly 
       if (customCostlistAdapter != null && customCostlistAdapter.getCount() > 0){ 

        // update 2nd element from arraylist 
        ProductDetails productDetails = new ProductDetails(); 
        productDetails.setProductName("Updated product"); 
        productDetails.setProductPrice(5555); 
        productCostDetails.set(2,productDetails); 

        // make changes in list 
        // this is magical line 
        customCostlistAdapter.notifyDataSetChanged(); 
       } 
      } 
     }); 

現在您可以創建產品成本細節自定義適配器(對於自定義listview)

/** 
    * Custom class for set product price details 
    */ 
    private class CustomCostlistAdapter extends BaseAdapter{ 
     LayoutInflater layoutInflater = getLayoutInflater(); 
     @Override 
     public int getCount() { 
      return productCostDetails.size(); 
     } 

     @Override 
     public Object getItem(int position) { 
      return null; 
     } 

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

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View productCostDetailView = layoutInflater.inflate(R.layout.custom_product_costview,null); 
      // create view for product 
      TextView productName = (TextView)productCostDetailView.findViewById(R.id.txtProductName); 
      TextView productPrice = (TextView)productCostDetailView.findViewById(R.id.txtProductPrice); 
      //set values 
      productName.setText(productCostDetails.get(position).getProductName()); 
      productPrice.setText(productCostDetails.get(position).getProductPrice()+""); 

      return productCostDetailView; 
     } 
    }