添加和删​​除自定义项目到列表视图

时间:2017-05-09 21:43:04

标签: java android listview listadapter custom-adapter

目前我正在添加一个自定义行(包含和编辑文本以及用于添加/删除行的加号和减号)到列表视图。但是,每次添加行时,都会擦除所有编辑文本中的内容。

public class ingredientView extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;



public ingredientView(ArrayList<String> list, Context context) {
    this.list = list;
    this.context = context;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int pos) {
    return list.get(pos);
}

@Override
public long getItemId(int pos) {
    return 0;
    //just return 0 if your list items do not have an Id variable.
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.ingredient_item, null);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, loadedFood);

    //Handle TextView and display string from your list
    InstantAutoComplete listItemText = (InstantAutoComplete) view.findViewById(R.id.recipe_ingredients);
    listItemText.setAdapter(adapter);

    listItemText.setText(list.get(position));

    //Handle buttons and add onClickListeners
    ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.ingredient_minus_button);
    ImageButton addBtn = (ImageButton)view.findViewById(R.id.ingredient_plus_button);

    deleteBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            //do something
            if (list.size()>1){
                list.remove(position); //or some other task
                notifyDataSetChanged();}
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            //do something
            list.add(position+1,"");
            notifyDataSetChanged();

        }
    });

    return view;
}


private static final String[] loadedFood = new String[]{
        "eggs","milk","butter","flour"

};

}

0 个答案:

没有答案