#android #listview #android-listview #listactivity #listadapter
#Android #listview #android-listview #listactivity #listadapter
Вопрос:
У меня есть ListActivity, в котором я показываю некоторые записи. Как только запись выбрана, я показываю другое действие с содержимым записи. Я бы хотел, когда я вернусь обратно к ListActivity, чтобы непрочитанные записи имели цвет, отличный от прочитанных.
У меня есть база данных, в которой хранятся записи, и когда я выбираю одну из них, поле базы данных COLUMN_READ обновляется.
У меня есть пользовательский ListAdapter:
public class CustomListAdapter extends SimpleCursorAdapter{
private Context context;
private int layout;
public CustomListAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
int titleCol = c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_TITLE);
int authorCol=c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_AUTHOR_NAME);
int readCol= c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_READ);
String title = c.getString(titleCol);
String author = c.getString(authorCol);
long read= c.getLong(readCol);
TextView name_text = (TextView) v.findViewById(R.id.title);
if (name_text != null) {
name_text.setText(title);
}
TextView content_text = (TextView) v.findViewById(R.id.subtitle);
if (content_text != null) {
content_text.setText(author);
}
if (read!=0){
name_text.setBackgroundColor(Color.GRAY);
}
return v;
}
@Override
public void bindView(View v, Context context, Cursor c) {
int titleCol = c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_TITLE);
int authorCol=c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_AUTHOR_NAME);
int readCol= c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_READ);
String title = c.getString(titleCol);
String author = c.getString(authorCol);
long read= c.getLong(readCol);
TextView name_text = (TextView) v.findViewById(R.id.title);
if (name_text != null) {
name_text.setText(title);
}
TextView content_text = (TextView) v.findViewById(R.id.subtitle);
if (content_text != null) {
content_text.setText(author);
}
if (read!=0){
name_text.setBackgroundColor(Color.GRAY);
}
}
}
И что я делаю, это:
CustomListAdapter present = new CustomListAdapter(context,
R.layout.atom_list_row, loadingCursor, new String[] {DataBaseSchema.EntrySchema.COLUMN_TITLE,DataBaseSchema.EntrySchema.COLUMN_AUTHOR_NAME, DataBaseSchema.EntrySchema.COLUMN_READ}, new int[]{R.id.title,R.id.subtitle,R.id.row_container});
setListAdapter(present);
Проблема в том, что выделенные записи отображаются некорректно, и я не понимаю, почему. Цвет фона фактически меняется для выбранной записи, но также и для некоторых других, кажется случайным, а также при прокрутке других записей меняется их цвет.
Это ошибка Android? Есть ли какое-то обходное решение, или я что-то упускаю?
Заранее спасибо..
РЕДАКТИРОВАТЬ Я нашел решение!!!! Я добавил v.refreshDrawableState();
в конце своего кода. Этот код работает:
public class CustomListAdapter extends SimpleCursorAdapter{
private Context context;
private int layout;
public CustomListAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
int titleCol = c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_TITLE);
int authorCol=c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_AUTHOR_NAME);
int readCol= c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_READ);
String title = c.getString(titleCol);
String author = c.getString(authorCol);
long read= c.getLong(readCol);
TextView name_text = (TextView) v.findViewById(R.id.title);
if (name_text != null) {
name_text.setText(title);
}
TextView content_text = (TextView) v.findViewById(R.id.subtitle);
if (content_text != null) {
content_text.setText(author);
}
if (read!=0){
v.setBackgroundColor(Color.GRAY);
}
else v.setBackgroundColor(Color.BLACK);
v.refreshDrawableState();
return v;
}
@Override
public void bindView(View v, Context context, Cursor c) {
int titleCol = c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_TITLE);
int authorCol=c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_AUTHOR_NAME);
int readCol= c.getColumnIndex(DataBaseSchema.EntrySchema.COLUMN_READ);
String title = c.getString(titleCol);
String author = c.getString(authorCol);
//long read= c.getLong(readCol);
TextView name_text = (TextView) v.findViewById(R.id.title);
if (name_text != null) {
name_text.setText(title);
}
TextView content_text = (TextView) v.findViewById(R.id.subtitle);
if (content_text != null) {
content_text.setText(author);
}
//LinearLayout linear =(LinearLayout) v.findViewById(R.id.row_container);
if (c.getLong(readCol)!=0){
v.setBackgroundColor(Color.GRAY);
}else v.setBackgroundColor(Color.BLACK);
v.refreshDrawableState();
}
}
Комментарии:
1. попробуйте использовать c.getLong(readCol)!=0 в NewView, а не read!=0 , все, что я хочу сказать, это избегать новой переменной. это то, что вызывает проблему.
2. Это не меняет поведение ListView, я хотел бы добавить, что похоже, что цвет фона меняется периодически (например, каждые 5 записей).
Ответ №1:
прочтите это, у вас может быть представление о цветном элементе в listview
Комментарии:
1. Я использую CursorAdapter, а не SimpleAdapter, потому что мне нужно иметь дело с базой данных. Метод getView в этом руководстве должен иметь ту же функцию, что и BindView в моем коде. Странно то, что это работает некорректно.
2. можете ли вы опубликовать свой основной класс, я думаю, что ему не хватает позиции идентификатора, поэтому получается случайным образом
3. немного сложно публиковать все здесь, извините. Я думаю, что то, что я уже опубликовал, — это единственное, что нужно.