创建自定义行布局 - 例如 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 布局中指定的项目。然后,您可以根据需要操作对象。