2012-12-27 108 views
0

Android有点问题。 硅继承人怎么回事,我有一个自定义适配器的ListView,什么IAM特林做的是动态地添加行,继承人的代码:Android将行添加到带有自定义适配器的ListView

适配器:

public class ProductAdapter extends ArrayAdapter<Product>{ 

    Context context; 
    int layoutResourceId;  
    String data[] = null; 

    public ProductAdapter(Context context, int layoutResourceId,String[] data) { 
     super(context, layoutResourceId); 
     this.layoutResourceId = layoutResourceId; 
     this.context = context; 
     this.data=data; 

    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View row = convertView; 
     ProductHolder holder = null; 

     if(row == null) 
     { 
      LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
      row = inflater.inflate(layoutResourceId, parent, false); 

      holder = new ProductHolder(); 
      holder.nameText = (TextView)row.findViewById(R.id.product_name); 
      holder.quantityText = (EditText)row.findViewById(R.id.quan_text); 

      row.setTag(holder); 
     } 
     else 
     { 
      holder = (ProductHolder)row.getTag(); 
     } 


     Product product = DBAdaptor.getProductByName(data[position]); 
     holder.img=(ImageView)row.findViewById(R.id.imgIcon); 
     holder.nameText.setText(product.getName()); 
     holder.quantityText.setText(" "); 

     return row; 
    } 



    static class ProductHolder 
    { 
     ImageView img; 
     TextView nameText; 
     EditText quantityText; 
    } 
} 

这里是我的主要活动:

public class Main extends Activity 
{ 
    public ListView lstView; 
    ProductAdapter productListAdapter; 
    DBAdaptor mDb; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
     { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main_screen); 
     openDB(); 
     productListAdapter = new ProductAdapter(this,  R.layout.shoping_list_row,getAllProducts()); 
     Bundle b = this.getIntent().getExtras(); 
     if(b!=null) 
     { 
      Product p =(Product) b.getSerializable("Product"); 
      productListAdapter.add(p); 
      productListAdapter.notifyDataSetChanged(); 
     } 


    } 


} 

世界上没有错误来了,但没有什么是被add'd到ListView

类Reggards,

回答

0

ArrayAdapter严重依赖于它自己的私有数组。你应该在适当的超级构造函数传递data

super(context, layoutResourceId, data); 

然后,你需要改变这一行:

Product product = DBAdaptor.getProductByName(data[position]); 

要:

Product product = DBAdaptor.getProductByName(getItem(position)); 

(你也不需要调用notifyDataSetChanged()使用方法如ArrayAdapter#add(),它会为您拨打notifyDataSetChanged()。)


如果你希望你的适配器使用本地的data副本,你将需要重写getCount()getItem()add()等使用data ...但你的时间已经改正了,你会不会使用一切大部分的ArrayAdapter,你也可以扩展BaseAdapter。

虽然看起来你想使用数据库(openDB())。您应该使用Cursors和CursorAdapters,因为它们比将表转换为Array更高效。

相关问题