I'm writing an android program for adding task and deleting task in listview. I've add an onClickListener to the delete button so it can delete the task. However I was told I should not have the listener in the adapter violating mvc. So can someone help me how I can remove a task in my TaskListItem class. I got the method removeTask() in the adapter, but don't how I can use it in the TaskListItem class. Thanks.
-
Code:
public TaskListItem(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
// locate the textViews
protected void onFinishInflate(){
super.onFinishInflate();
taskName = (TextView) findViewById(R.id.the_task);
resp = (TextView) findViewById(R.id.resp);
prio = (TextView) findViewById(R.id.prio);
}
// getter and setter for the bin button
public ImageView getBinIcon() { return binIcon; }
public void setBinIcon(ImageView binIcon) { this.binIcon = binIcon; }
public Task getTask() { return task; }
// set the text for the textViews
public void setTask(Task task) {
String currentResp = resp.getText().toString();
String currentPrio = prio.getText().toString();
this.task = task;
taskName.setText(task.getName());
resp.setText(currentResp + task.getResponsible());
prio.setText(currentPrio + task.getPriority());
binIcon = (ImageView) findViewById(R.id.bin_icon);
binIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { /** delete task */ }
});
}
-
Code:
public class TaskListAdapter extends BaseAdapter {
private ArrayList<Task> tasks;
private Context context;
private int position;
public TaskListAdapter(ArrayList<Task> tasks, Context context) {
super();
this.tasks = tasks;
this.context = context;
}
public int getCount() { return tasks.size(); }
public Object getItem(int position) {
return (null == tasks) ? null: tasks.get(position);
}
public long getItemId(int position) { return position; }
/**
* set the view
* set the task and bin icon from TaskListItem
* add listener bin icon, when clicked the a task is removed from the array list task
*/
public View getView(final int position, View convertView, ViewGroup parent) {
TaskListItem tli;
if(null == convertView){
tli =(TaskListItem)View.inflate(context, R.layout.task_list_items, null);
this.position = position;
//tli.setBinIcon((ImageView) tli.findViewById(R.id.bin_icon));
}
else { tli = (TaskListItem)convertView; }
tli.setTask(tasks.get(position));
/*
tli.getBinIcon().setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tasks.remove(position);
notifyDataSetChanged();
}
});
*/
return tli;
}
public void removeTask(){
tasks.remove(position);
notifyDataSetChanged();
}
}