Creating custom simple cursor adapter

非 Y 不嫁゛ 提交于 2019-11-30 15:03:10

You should be able to do it about that way:

class YourListFragment extends ListFragmentOrSomethingElse {
    private AreaCursorAdapter mAdapter;

    @Override    
    public void onCreate() {
        mAdapter = new AreaCursorAdapter(this, null);
        setListAdapter(mAdapter);
    }

    @Override
    public void onListItemClick(ListView parent, View v, int position, long id) { 
        mAdapter.setSelectedPosition(position);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        mAdapter.swapCursor(cursor);
        // should reset that here maybe
        mAdapter.setSelectedPosition(-1);
    }
}

public class AreaCursorAdapter extends CursorAdapter {
    private Context context;
    private int mSelectedPosition;
    LayoutInflater mInflater;

    public AreaCursorAdapter(Context context, Cursor c) {
        // that constructor should be used with loaders.
        super(context, c, 0);
        mInflater = LayoutInflater.from(context);
    }

    public void setSelectedPosition(int position) {
        mSelectedPosition = position;
        // something has changed.
        notifyDataSetChanged();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView list_item = (TextView)view.findViewById(android.R.id.text1);
        list_item.setText(cursor.getString(cursor.getColumnIndex(INDICATOR_NAME)));
        int position = cursor.getPosition(); // that should be the same position
        if (mSelectedPosition == position) {
           view.setBackgroundColor(Color.RED);
        } else {
           view.setBackgroundColor(Color.WHITE);
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
        // edit: no need to call bindView here. That's done automatically
        return v;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!