Создание собственного адаптера простого курсора - PullRequest
5 голосов
/ 13 марта 2012

Я хочу создать очень простой пользовательский адаптер курсора курсора, чтобы облегчить изменение цвета элементов строки при щелчке.Используя следующий код

private static int save = -1;

public void onListItemClick(ListView parent, View v, int position, long id) { 

    parent.getChildAt(position).setBackgroundColor(Color.BLUE);

    if (save != -1 && save != position){
        parent.getChildAt(save).setBackgroundColor(Color.BLACK);
    }

    save = position;                

}

Я получил код из этой темы https://stackoverflow.com/a/7649880/498449

Я бы использовал простой адаптер курсора и поместил код в onClick, но потому что список по умолчаниюв ListFragment повторно используются представления, так как при прокрутке несколько представлений отображаются подсвеченными.Говоря о IRC, было предложено создать собственный адаптер курсора.Тем не менее, я не могу найти наилучшую практику, как это сделать, и где поместился бы приведенный выше фрагмент кода. Могу высоко оценить помощь.

public class AreaCursorAdapter extends CursorAdapter {
    private Context context;


    public AreaCursorAdapter(Context context, Cursor c) {
        super(context, c);
        // TODO Auto-generated constructor stub
    }

    @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)));

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
    bindView(v, context, cursor);
    return v;
}

}

Я обновил адаптер курсорас некоторым кодом, который я нашел в Интернете.Однако у меня есть две проблемы.1. Я использую загрузчик курсора, поэтому у меня нет объекта «курсор» для передачи в конструктор.2. Я получаю предупреждение от Eclipse, что конструктор устарел.

1 Ответ

18 голосов
/ 14 марта 2012

Вы должны быть в состоянии сделать это следующим образом:

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;
    }

}
...