Android使用自定义适配器向ListView添加行

时间:2012-12-27 22:32:15

标签: android android-listview android-adapter

有一些android的问题。 Si继续发生什么,我有一个带有自定义适配器的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();
        }


    }


}

Theres没有出现错误,但没有添加到listView

亲切的问候,

1 个答案:

答案 0 :(得分: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和CursorAdapter,因为它们比将表转换为数组更有效。