2

ListView这个问题中,我已经为我的特定项目取得了类似的成就。

但是,现在,我希望用户能够单击项目,这实际上会突出显示用户点击的任何项目。我在我的应用程序中保留了一个被点击项目的列表,并且应该能够ViewBinder在滚动发生时引用它,但是,因为我从来没有调整任何东西来适应LinearLayoutListView本身,我不知道如何获取LinearLayout对象为了正确设置其背景颜色。

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

4

2 回答 2

1

创建自定义行布局 - 例如 custom_row.xml,并安排所需的任何视图,就像在活动的正常布局中一样(因此在这种情况下,您可能会为文本提供一个 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 布局中指定的项目。然后,您可以根据需要操作对象。

于 2011-07-05T19:01:57.123 回答
0

我相信一种方法是使用状态列表,其中默认状态具有透明背景,而选定状态具有您想要的背景。

例如,请参阅 Romain Guy 的回答: 在 Android 上更改 ListView 项目的背景颜色

另请参阅:Android ListView 状态列表未显示默认项目背景

于 2011-07-05T18:21:18.077 回答