android - 如何让我的 ListView 项目具有(并保持)不同的背景?

标签 android background android-listview android-viewbinder

我在 this 中的 ListView 中针对特定项目实现了类似的效果|问题。

但是,现在,我希望用户能够点击项目,这实际上会突出显示用户点击的任何项目。我在我的应用程序中保留了一个点击项目的列表,并且应该能够在发生滚动时从 ViewBinder 中引用它,但是,因为我从未对 LinearLayout 进行任何调整> 构成 ListView 本身,我不确定如何获取 LinearLayout 对象以便正确设置其背景颜色。

我需要能够做到这一点,因为您可能知道,在滚动时,Android 会重新使用列表项,这很好,除非您要更改单个列表项的格式(着色等)。在这种情况下,您最终会得到颜色/格式不正确的列表项。当涉及到列表项中的 TextViews 时,我正在使用 ViewBinder 来解决问题,但不知道如何为 的背景做类似的事情>ListView 本身。

最佳答案

创建自定义行布局 - 例如custom_row.xml,并安排任何需要的 View ,就像您在 Activity 的正常布局中所做的那样(因此在这种情况下,您可能会为文本提供一个 TextView ,并且可能在其左侧提供一个图标)。

然后通过扩展现有适配器创建您的自定义适配器,并照此覆盖 getView 方法。下面是一个使用带有标题和副标题的布局 custom_row 的示例:

class CustomAdapter<T> extends ArrayAdapter<T> {

/** List item title */
protected TextView mTitle;
/** List item subtitle */
protected TextView mSubtitle;

/**
 * @param context
 *            Current context
 * @param items
 *            Items being added to the adapter
 */
public CustomAdapter(final Context context, final List<T> items) {
    super(context, R.layout.custom_row, items);
}

/** Construct row */
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        final LayoutInflater li = (LayoutInflater) getContext().getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        view = li.inflate(R.layout.custom_row, null);
    }
    mTitle = (TextView) view.findViewById(R.id.custom_row_title);
    mSubtitle = (TextView) view.findViewById(R.id.custom_row_subtitle);
    return view;
}
}

如前所述,您可以获取在您通过 inflater 服务创建的 custom_row 布局中指定的项目。然后您可以根据需要操作对象。

关于android - 如何让我的 ListView 项目具有(并保持)不同的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6586614/

相关文章:

java - 如何在Android应用程序中正确实现android.os.Handler类而不是Timer?

java - Android:将简单的光标链接到 ListView

java - listview 1 Activity 用于打开 listview 2 Activity

android - 如何在 Android native 中使用 Facebook OAuth?

java - Android 连接到 MJPEG 流 - 权限被拒绝错误

android - android.os.Looper 中的方法 myLooper 未使用协程模拟

jQuery 交叉淡入淡出与背景图像

ios - 当用户进入后台模式时使用 viewWillDisappear

background - Gnuplot 绘图区域背景

android - 在 FragmentTransaction 之后调用什么方法