无法将背景颜色设置为自定义 CursorAdapter 中的列表项

Unable set background color to List item in Custom CursorAdapter

我正在尝试为我的列表视图提供替代背景颜色。我正在使用游标适配器。 这是我的 CustomCursorAdapter class

CustomCursorAdapter.java

public class CustomCursorAdapter extends CursorAdapter {

public CustomCursorAdapter(Context context, Cursor c) {
    super(context, c);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View retView = inflater.inflate(R.layout.single_row_item, parent, false);

    return retView;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {

    TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
    textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    final View row = super.getView(position, convertView, parent);
    if (position % 2 == 0)
        row.setBackgroundColor(Color.parseColor("#191919"));
    else
        row.setBackgroundColor(Color.parseColor("#323232"));
    return row;

}
}

在getView()中;我有 setBackgroundColor 来查看。但它们没有得到正确分配,只有 texview 背景颜色受到影响。这是我的 single_row_item.xml

single_row_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageView2"
        android:src="@drawable/icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/tv_person_name"
        android:layout_marginLeft="10dp" />
</LinearLayout>

这是我的输出。请告诉我该怎么做。

尝试将设置替代行颜色的逻辑移动到 bindView() 方法而不是 getView()

在 CursorAdapter 中,您在 newView() 中获取布局并在 bindView() 中绑定数据。 CursorAdapter 已经在 getView() 中执行了重用模式,因此您无需再次执行。

CursorAdaptergetView() 委托给 newView()bindView()。 因此 getView() 方法使用视图回收机制以及将行构造委托给 newView()bindView() 方法。

这意味着在 CursorAdapter 的情况下,所有这些都通过实施 newView()bindView().

为您处理

我找到了答案。这只是一个愚蠢的小错误。在我的 Activity 的 XML 中,我有列表视图。该列表视图的宽度应为 "fill_parent" 或 "match_parent".