如何将视图添加到 ListView?

How do I add Views to a ListView?

我遇到的每个 example/tutorial 都只是将字符串添加到 ListView,但我想添加膨胀的视图。我已经测试了膨胀视图,如果我使用 addView() 将它添加到某个 ViewGroup(如 RelativeLayout),它看起来很好。但是将膨胀视图添加到ListView只是以文本形式显示:

ArrayList<View> friend_request_items = new ArrayList<View>();  //a list containing the items we want to add 

ListView friend_request_list = (ListView) findViewById( R.id.friend_request_list );

ArrayAdapter<View> friend_request_adapter = new ArrayAdapter<View>( this, android.R.layout.simple_list_item_1, friend_request_items);

friend_request_list.setAdapter( friend_request_adapter );

//friend_template is just my own xml file containing the view I'm inflating
View friend_request_item = LayoutInflater.from(this).inflate(R.layout.friend_template, null);

friend_request_items.add( friend_request_item ); 
friend_request_adapter.notifyDataSetChanged();

我认为问题是我传递给适配器的布局,但我不知道将其更改为什么(或者这是否是解决方案)。

这是一个很好的教程,使用自定义 ArrayAdapter 和自定义 xml 布局 Using lists in Android。 您应该 subclass 一个 ArrayAdapter 并在 getView 方法中膨胀一行,这是一种常见且有效的解决方案,而不是将视图作为列表的通用参数传递,您应该传递数据 class,例如 ArrayAdapter<FriendRequest> 或类似的

public class FriendRequestsAdapter extends ArrayAdapter<FriendRequest> {
private LayoutInflater inflater;

public FriendRequestsAdapter(Context context, List<FriendRequest> requests) {
    super(context, R.layout.friend_request_row, requests);
    this.inflater = ((Activity)context).getLayoutInflater();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.friend_request_row, parent, false);
    }

    FriendRequest item = getItem(position);
    TextView textView = (TextView) convertView.findViewById(R.id.textView);

    return convertView;
}

}

Every example/tutorial I've come across just adds Strings to ListViews

还有其他示例,但您不太可能找到所提议内容的示例。

I want to add inflated Views

A ListAdapter returns "inflated Views" 来自它的 getView() 方法。具体如何操作由您决定。

此外,ListView 背后的要点是能够回收列表行 Views,因为列表可能很大,而行在堆方面的开销很大 space。您的代码似乎预先创建了所有行视图,这仅适用于小型数据集。

But adding the inflated view to the ListView just displays it in the form of text

ListViewArrayAdapter 上调用 getView() 时,ArrayAdapter 获取所需行的模型,对其调用 toString(),然后将其注入a TextView 由您的其他构造函数参数标识(在本例中,TextView 格式如 android.R.id.simple_list_item_1 中定义)。

I think the problem is the layout I'm passing into the adapter, but I don't know what to change it to (or if this is even the solution).

首先,我强烈建议您重新考虑您最初的心态 ("I want to add inflated Views")。请记住,您必须处理配置更改(例如,屏幕旋转、区域设置更改)和进程终止,并且您的 "inflated Views" 在任何一种情况下都会消失。 ListViewListAdapter 旨在将 模型数据 转换为适当的视觉表示,并以节省内存的方式进行。

话虽如此,如果您完全相信自己的整体方法,则需要创建一个自定义 BaseAdapterArrayAdapter 子类,其中 getView() 您 return 给定 position.

所需的 "inflated View"