这个自定义的CursorAdapter用于Android中的ListView,代码编写正确吗?

11

我一直对我的自定义CursorAdapter的代码不太满意,直到今天我决定重新审视它并解决一个一直困扰我的小问题(有趣的是,我的应用程序的用户从未报告过这样的问题)。

以下是我的问题的简要描述:

我的自定义CursorAdapter覆盖了newView()bindView()方法,而不是像大多数示例那样覆盖getView()方法。我在这两个方法之间使用ViewHolder模式。但是我的主要问题是我为每个列表项使用的自定义布局,其中包含一个ToggleButton

问题在于当列表项视图滚动出视图然后再滚回视图时,按钮状态没有保留。这个问题存在的原因是cursor没有意识到当按下ToggleButton时数据库数据已经改变,它总是拉取相同的数据。我尝试在单击ToggleButton时重新查询游标以解决问题,但速度非常慢。

我已经解决了这个问题,并在此处发布整个类供审查。我已经针对这个特定问题详细注释了代码,以更好地解释我的编码决策。

你认为这段代码看起来不错吗?你会改进/优化或以某种方式更改它吗?

P.S:我知道CursorLoader是一个明显的改进,但目前我没有时间处理这样庞大的代码重写。不过这是我计划中的事情。

以下是代码:

public class NotesListAdapter extends CursorAdapter implements OnClickListener {

    private static class ViewHolder {
        ImageView icon;
        TextView title;
        TextView description;
        ToggleButton visibility;
    }

    private static class NoteData {
        long id;
        int iconId;
        String title;
        String description;
        int position;
    }

    private LayoutInflater mInflater;

    private NotificationHelper mNotificationHelper;
    private AgendaNotesAdapter mAgendaAdapter;

    /*
     * This is used to store the state of the toggle buttons for each item in the list
     */
    private List<Boolean> mToggleState;

    private int mColumnRowId;
    private int mColumnTitle;
    private int mColumnDescription;
    private int mColumnIconName;
    private int mColumnVisibility;

    public NotesListAdapter(Context context, Cursor cursor, NotificationHelper helper, AgendaNotesAdapter adapter) {
        super(context, cursor);

        mInflater = LayoutInflater.from(context);

        /*
         * Helper class to post notifications to the status bar and database adapter class to update
         * the database data when the user presses the toggle button in any of items in the list
         */
        mNotificationHelper = helper;
        mAgendaAdapter = adapter;

        /*
         * There's no need to keep getting the column indexes every time in bindView() (as I see in
         * a few examples) so I do it once and save the indexes in instance variables
         */
        findColumnIndexes(cursor);

        /*
         * Populate the toggle button states for each item in the list with the corresponding value
         * from each record in the database, but isn't this a slow operation?
         */
        for(mToggleState = new ArrayList<Boolean>(); !cursor.isAfterLast(); cursor.moveToNext()) {
            mToggleState.add(cursor.getInt(mColumnVisibility) != 0);
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = mInflater.inflate(R.layout.list_item_note, null);

        /*
         * The ViewHolder pattern is here only used to prevent calling findViewById() all the time
         * in bindView(), we only need to find all the views once
         */
        ViewHolder viewHolder = new ViewHolder();

        viewHolder.icon = (ImageView)view.findViewById(R.id.imageview_icon);
        viewHolder.title = (TextView)view.findViewById(R.id.textview_title);
        viewHolder.description = (TextView)view.findViewById(R.id.textview_description);
        viewHolder.visibility = (ToggleButton)view.findViewById(R.id.togglebutton_visibility);

        /*
         * I also use newView() to set the toggle button click listener for each item in the list
         */
        viewHolder.visibility.setOnClickListener(this);

        view.setTag(viewHolder);

        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        Resources resources = context.getResources();

        int iconId = resources.getIdentifier(cursor.getString(mColumnIconName),
                "drawable", context.getPackageName());

        String title = cursor.getString(mColumnTitle);
        String description = cursor.getString(mColumnDescription);

        /*
         * This is similar to the ViewHolder pattern and it's need to access the note data when the
         * onClick() method is fired
         */
        NoteData noteData = new NoteData();

        /*
         * This data is needed to post a notification when the onClick() method is fired
         */
        noteData.id = cursor.getLong(mColumnRowId);
        noteData.iconId = iconId;
        noteData.title = title;
        noteData.description = description;

        /*
         * This data is needed to update mToggleState[POS] when the onClick() method is fired
         */
        noteData.position = cursor.getPosition();

        /*
         * Get our ViewHolder with all the view IDs found in newView()
         */
        ViewHolder viewHolder = (ViewHolder)view.getTag();

        /*
         * The Html.fromHtml is needed but the code relevant to that was stripped
         */
        viewHolder.icon.setImageResource(iconId);
        viewHolder.title.setText(Html.fromHtml(title));
        viewHolder.description.setText(Html.fromHtml(description));

        /*
         * Set the toggle button state for this list item from the value in mToggleState[POS]
         * instead of getting it from the database with 'cursor.getInt(mColumnVisibility) != 0'
         * otherwise the state will be incorrect if it was changed between the item view scrolling
         * out of view and scrolling back into view
         */
        viewHolder.visibility.setChecked(mToggleState.get(noteData.position));

        /*
         * Again, save the note data to be accessed when onClick() gets fired
         */
        viewHolder.visibility.setTag(noteData);
    }

    @Override
    public void onClick(View view) {
        /*
         * Get the new state directly from the toggle button state 
         */
        boolean visibility = ((ToggleButton)view).isChecked();

        /*
         * Get all our note data needed to post (or remove) a notification 
         */
        NoteData noteData = (NoteData)view.getTag();

        /*
         * The toggle button state changed, update mToggleState[POS] to reflect that new change
         */
        mToggleState.set(noteData.position, visibility);

        /*
         * Post the notification or remove it from the status bar depending on toggle button state
         */
        if(visibility) {
            mNotificationHelper.postNotification(
                    noteData.id, noteData.iconId, noteData.title, noteData.description);
        } else {
            mNotificationHelper.cancelNotification(noteData.id);
        }

        /*
         * Update the database note item with the new toggle button state, without the need to
         * requery the cursor (which is slow, I've tested it) to reflect the new toggle button state
         * in the list because the value was saved in mToggleState[POS] a few lines above
         */
        mAgendaAdapter.updateNote(noteData.id, null, null, null, null, visibility);
    }

    private void findColumnIndexes(Cursor cursor) {
        mColumnRowId = cursor.getColumnIndex(AgendaNotesAdapter.KEY_ROW_ID);
        mColumnTitle = cursor.getColumnIndex(AgendaNotesAdapter.KEY_TITLE);
        mColumnDescription = cursor.getColumnIndex(AgendaNotesAdapter.KEY_DESCRIPTION);
        mColumnIconName = cursor.getColumnIndex(AgendaNotesAdapter.KEY_ICON_NAME);
        mColumnVisibility = cursor.getColumnIndex(AgendaNotesAdapter.KEY_VISIBILITY);
    }

}
3个回答

4
您的解决方案是最优的,我将把它加入我的武器库 :) 或许,我会尝试为对数据库调用进行一些小优化。
由于任务条件,实际上只有三种解决方案:
1. 仅更新一行,重新查询游标并重绘所有项(直接而傻瓜式)。 2. 更新行,缓存结果并使用缓存来绘制项。 3. 缓存结果,使用缓存来绘制项。当您离开此活动/片段时,将结果提交到数据库。
对于第三个解决方案,您可以使用SparseArray来查找更改内容。
private SparseArray<NoteData> mArrayViewHolders;

public void onClick(View view) {
     //here your logic with NoteData. 
     //start of my improve
     if (mArrayViewHolders.get(selectedPosition) == null) {
        // put the change into array
        mArrayViewHolders.put(selectedPosition, noteData);
     } else {
        // rollback the change
        mArrayViewHolders.delete(selectedPosition);
     }
     //end of my improve
     //we don't commit the changes to database.
}

再次强调:一开始这个数组是空的。当你第一次切换按钮(发生更改)时,你会向数组中添加NoteData。当你第二次切换按钮(发生回滚)时,你会从数组中删除NoteData。以此类推。

当你完成时,只需请求该数组并将更改推送到数据库中即可。


我喜欢“SparseArray”这个概念,之前不知道这个类。使用它看起来比将所有按钮状态保存在“List”中更高效。但是,我不喜欢只有在用户离开活动时才将结果提交到数据库的想法。那需要额外的代码来处理该情况。所以,最终,我想我还是选择了你列举的第二种解决方案。这基本上就是我一开始做的事情。我仍然喜欢你的答案,但是我可能需要再考虑1或2天 :) - rfgamaral

1

你所看到的是 Android 中视图重用的方式。我认为你再次查询游标并没有做错什么。只是不要使用 cursor.requery() 函数。

相反,始终将开关设置为 false,然后询问游标并在必要时打开它。

也许你正在这样做,而我误解了一些东西,但我认为你不应该因此获得缓慢的结果。

伪代码:

getView(){
setToggleFalse();
boolean value = Boolean.valueOf(cursor.getString('my column'));
if (value){
   setToggleTrue();
}
}

1

在使用CursorLoader之前,我建议先等待一下。因为似乎CursorLoader的衍生产品与CursorLoader不兼容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接