如何使用自定义baseadapter在列表中添加/删除项目

时间:2011-11-10 00:14:23

标签: android baseadapter

我在这里有一个基于我在API演示中看到的baseadapter。我想动态添加/删除列表中的项目,在这种情况下,从按钮调用的意图添加,并从列表视图中单击图像视图中删除。在这种情况下,我将添加/删除DATA []中的项目。 我在SO和谷歌上四处寻找各种AddItem()和/或Remove()方法,但对于这种情况并没有真正想出什么。任何帮助都会很棒。这是代码:

public class myActivity extends Activity{
    private static final int CONTACT_PICKER_RESULT = 1001;  
    private static final String TAG = myActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView lv = (ListView)findViewById(R.id.listView1);
        lv.setAdapter(new myAdapter(this));     
        Button bAdd = (Button)findViewById(R.id.bAdd);
        bAdd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
        ........xxxx....xxxx....
        }
public class myAdapter extends BaseAdapter{
        private LayoutInflater mInflater;

        public myAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return DATA.length;
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }


        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.row,null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.txtTitle);
                holder.icon = (ImageView) convertView.findViewById(R.id.imgIcon);
                convertView.setTag(holder);


            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }
            holder.text.setText(DATA[position]);
            holder.icon.setImageResource(android.R.drawable.ic_delete);

            return convertView;
        }



        }


    static class ViewHolder {
        TextView text;
        ImageView icon;
    }
//this will not be hard-coded, jsut included for clarity
private static final String[] DATA ={
        "one","two","three" };

1 个答案:

答案 0 :(得分:1)

如果你需要做的就是在DATA []数组中添加/删除项目,为什么不用简单的List替换数组,例如由ArrayList实现。

这将允许您为适配器编写单击处理程序,根据需要在列表中添加/删除项目。