gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:12:19 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com