如何从Android中的适配器中的事件侦听器刷新ListView自定义适配器数据?

时间:2016-01-26 10:08:26

标签: android listview android-adapter

我绝对是Android的初学者。现在我使用自定义适配器和自定义视图使用ListView。自定义适配器创建为单独的文件。但是在我的自定义适配器中,我为列表视图行的布局按钮设置了一个单击侦听器。但我的问题是如何更新在自定义适配器内创建的事件侦听器内的适配器项。请参阅下面的方案。

这是我的Listview片段:

public class TaskListFragment extends Fragment {
    private DatabaseHelper dbHelper;
    private TextView taskTitle;
    private ListView taskListView;
    private ArrayAdapter adapter;
    private ArrayList<Task> items;
    private int optionFocusedItemIndex;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        dbHelper = new DatabaseHelper(getActivity());
        View view= inflater.inflate(R.layout.task_list, container, false);
        taskTitle = (TextView)view.findViewById(R.id.task_textview);
        taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
        int type = getArguments().getInt("type");
        switch (type){
            case R.integer.task_list_all:
                items = dbHelper.getAllTasks();
                adapter = new TaskListAdapter(getActivity(),items);
                taskListView.setAdapter(adapter);
                taskTitle.setText("All tasks");
                break;
        }
        taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                int tagId = Integer.valueOf(view.getTag().toString());
                optionFocusedItemIndex = position;
                showOptionDialog(tagId);
                return true;
            }
        });
        return view;
    }

    public void showOptionDialog(final int id)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        View view = layoutInflater.inflate(R.layout.row_option_dialog, null);

        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
        doneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.markAsDone(id);
                refreshListView();
                alertDialog.cancel();
                Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
            }
        });
        Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity activity = (MainActivity)getActivity();
                activity.replaceEditTaskFragment(id);
                alertDialog.cancel();
            }
        });
        Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.deleteTask(id);
                items.remove(optionFocusedItemIndex);
                adapter.notifyDataSetChanged();
                Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
                alertDialog.cancel();
            }
        });
        Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        alertDialog.setView(view);
        alertDialog.show();
    }

    public void refreshListView()
    {
        if(items!=null)
        {
            Task taskOld = items.get(optionFocusedItemIndex);
            if(taskOld!=null)
            {
                taskOld.setDone(true);
                items.set(optionFocusedItemIndex, taskOld);
                adapter.notifyDataSetChanged();
            }
        }
    }
}

在片段内部,当我单击完成按钮时,listView适配器已正确更新并且正在查找。完成按钮位于AlertDialog框内,当长按列表视图的其中一行时,该按钮会出现。

问题出在这里。

这是我的自定义适配器类:

public class TaskListAdapter extends ArrayAdapter<Task> {
    private final Context context;
    private final ArrayList<Task> values;
    private final DatabaseHelper dbHelper;
    public TaskListAdapter(Context context,ArrayList<Task> values)
    {
        super(context,-1,values);
        this.context = context;
        this.values = values;
        this.dbHelper = new DatabaseHelper(context.getApplicationContext());
    }

    @Override
    public View getView(final int position,View convertView,ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView  = inflater.inflate(R.layout.task_list_row,parent, false);
        rowView.setTag(values.get(position).getId());
        TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
        rowDescription.setText(values.get(position).getDescription());
        ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);

        Long currentDateMillSec= System.currentTimeMillis();
        Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
        if(values.get(position).getDone()==Boolean.TRUE)
        {
           rowStatusIcon.setImageResource(R.drawable.done_icon);
        }
        else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
        {
           rowStatusIcon.setImageResource(R.drawable.failed_icon);
        }
        else{
            rowStatusIcon.setImageResource(R.drawable.todo_icon);
        }


        TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
        dateTf.setText(values.get(position).getDate());

        Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
        doneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.markAsDone(values.get(position).getId());
                //How can I update the listview items here ?

            }
        });
        return rowView;
    }


}

那么如何从自定义适配器类内部的完成按钮的单击事件侦听器更新列表视图项和列表视图。

2 个答案:

答案 0 :(得分:0)

public class TaskListFragment extends Fragment implements TaskListAdapter.RefreshAdapter{//change
    private DatabaseHelper dbHelper;
    private TextView taskTitle;
    private ListView taskListView;
    private ArrayAdapter adapter;
    private ArrayList<Task> items;
    private int optionFocusedItemIndex;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    dbHelper = new DatabaseHelper(getActivity());
    View view= inflater.inflate(R.layout.task_list, container, false);
    taskTitle = (TextView)view.findViewById(R.id.task_textview);
    taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
    int type = getArguments().getInt("type");
    switch (type){
        case R.integer.task_list_all:
            items = dbHelper.getAllTasks();
            adapter = new TaskListAdapter(getActivity(),items);
            taskListView.setAdapter(adapter);
        adapter.setRefreshAdapter(this);//change
            taskTitle.setText("All tasks");
            break;
    }
    taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            int tagId = Integer.valueOf(view.getTag().toString());
            optionFocusedItemIndex = position;
            showOptionDialog(tagId);
            return true;
        }
    });
    return view;
    }

    public void showOptionDialog(final int id)
    {
    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
    View view = layoutInflater.inflate(R.layout.row_option_dialog, null);

    final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
    Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
    doneBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dbHelper.markAsDone(id);
            refreshListView();
            alertDialog.cancel();
            Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
        }
    });
    Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
    editBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity activity = (MainActivity)getActivity();
            activity.replaceEditTaskFragment(id);
            alertDialog.cancel();
        }
    });
    Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
    deleteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dbHelper.deleteTask(id);
            items.remove(optionFocusedItemIndex);
            adapter.notifyDataSetChanged();
            Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
            alertDialog.cancel();
        }
    });
    Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
    cancelBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alertDialog.cancel();
        }
    });
    alertDialog.setView(view);
    alertDialog.show();
    }

    public void refreshListView()
    {
    if(items!=null)
    {
        Task taskOld = items.get(optionFocusedItemIndex);
        if(taskOld!=null)
        {
            taskOld.setDone(true);
            items.set(optionFocusedItemIndex, taskOld);
            adapter.notifyDataSetChanged();
        }
    }
    }

    //change
    @Override
    public void OnlickRefreshAdapter(){
    //todo your code here
    items = dbHelper.getAllTasks();
    adapter = new TaskListAdapter(getActivity(),items);
        taskListView.setAdapter(adapter);
    }
}

适配器类

public class TaskListAdapter extends ArrayAdapter<Task> {
    private final Context context;
    private final ArrayList<Task> values;
    private final DatabaseHelper dbHelper;
    private RefreshAdapter refreshAdapter;
    public TaskListAdapter(Context context,ArrayList<Task> values)
    {
    super(context,-1,values);
    this.context = context;
    this.values = values;
    this.dbHelper = new DatabaseHelper(context.getApplicationContext());
    }

     public Interface RefreshAdapter{
        public void OnlickRefreshAdapter();
     }

     public setRefreshAdapter(RefreshAdapter refresh){
    refreshAdapter = refresh;
     }

    @Override
    public View getView(final int position,View convertView,ViewGroup parent)
    {
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView  = inflater.inflate(R.layout.task_list_row,parent, false);
    rowView.setTag(values.get(position).getId());
    TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
    rowDescription.setText(values.get(position).getDescription());
    ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);

    Long currentDateMillSec= System.currentTimeMillis();
    Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
    if(values.get(position).getDone()==Boolean.TRUE)
    {
       rowStatusIcon.setImageResource(R.drawable.done_icon);
    }
    else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
    {
       rowStatusIcon.setImageResource(R.drawable.failed_icon);
    }
    else{
        rowStatusIcon.setImageResource(R.drawable.todo_icon);
    }


    TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
    dateTf.setText(values.get(position).getDate());

    Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
    doneBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dbHelper.markAsDone(values.get(position).getId());
            //How can I update the listview items here ?

        }
    });
    return rowView;
    }

}

答案 1 :(得分:0)

我得到了答案,实际上它太简单了。我需要做的只是在自定义适配器中的完成按钮的单击侦听器中添加此代码。

这是自定义适配器中doneBtn的点击侦听器:

doneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.markAsDone(values.get(position).getId());
                //How can I update the listview items here ?
                if(values!=null)
                {
                    Task oldTask = values.get(position);
                    oldTask.setDone(Boolean.TRUE);
                    values.set(position,oldTask);
                    notifyDataSetChanged();
                }

            }
        });