如何刷新Android Listview只有新值
问题描述:
我想在列表视图中设置我的更新的适配器,但我有一个问题是,列表视图中的旧值仍然存在,并在下面,新值设置,所以我只想在列表视图中只设置新的刷新值。如何刷新Android Listview只有新值
答
试试这个,
这是例如,对于产品清单包含产品名称及成本。
我采取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;
}
}
添加一些相关的代码,你已经尝试过,那么我们将能够帮助你? –
发表你的代码请 – earthw0rmjim
它更好地使用RecyclerView .. https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html – fatboy