我在this问题的ListView
内为特定项目取得了类似的效果。
但是,现在,我希望用户能够点击项目,这将基本上突出显示用户点击的任何项目。我在应用程序中保留了已点击项目的列表,并且应该能够在滚动发生时从ViewBinder
引用此项,但是,因为我从不对构成LinearLayout
的{{1}}进行任何调整{1}}本身,我不知道如何获取ListView
对象以正确设置其背景颜色。
我需要能够这样做,因为您可能知道,在滚动时,Android会重新使用列表项,这很好,除非您要更改单个列表项的格式(着色等)。在这种情况下,您最终得到的颜色/格式不正确的列表项。我在列表项中使用LinearLayout
来解决问题,但不知道如何为ViewBinder
本身的背景做类似的事情。< / p>
答案 0 :(得分:1)
创建自定义行布局 - 例如custom_row.xml,并安排所需的任何视图,就像在活动的正常布局中一样(因此在这种情况下,您可能会为文本提供文本视图,也可能是左侧的图标)。
然后通过扩展现有适配器来创建自定义适配器,并覆盖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布局中指定的项目。然后,您可以根据需要操作对象。
答案 1 :(得分:0)
我认为一种方法是使用state list,其中默认状态具有透明背景,并且所选状态具有您想要的背景。
例如,请参阅Romain Guy的答案: Changing background color of ListView items on Android
另请参阅:Android ListView State List not showing default item background