0

我在这里有一个基于我在 API 演示中看到的基础适配器。我想从列表中动态添加/删除项目,在这种情况下,从按钮调用的意图添加,并从单击列表视图中的图像视图中删除。在这种情况下,我将在 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" };
4

1 回答 1

1

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

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

于 2011-11-10T00:28:39.303 回答