您可能应该手动将项目添加到LinearLayout
:
LinearLayout layout = ... // Your linear layout.
ListAdapter adapter = ... // Your adapter.
final int adapterCount = adapter.getCount();
for (int i = 0; i < adapterCount; i++) {
View item = adapter.getView(i, null, null);
layout.addView(item);
}
EDIT:当我需要显示大约 200 个重要的列表项时,我拒绝了这种方法,它非常慢 - Nexus 4 需要大约 2 秒来显示我的“列表”,这是不可接受的。所以我转向弗洛的头球方法。它的工作速度要快得多,因为列表视图是在用户滚动时按需创建的,而不是在创建视图时创建的。
Resume:手动将视图添加到布局更容易编码(因此可能会减少移动部件和错误),但会遇到性能问题,因此如果您有 50 个或更多视图,我建议使用标头方法。
例子。基本上,活动(或片段)布局转换为类似这样的内容(不再需要 ScrollView):
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_top_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Then in onCreateView()
(我将使用带有片段的示例)您需要添加标头视图,然后设置适配器(我假设标头资源 ID 是header_layout
):
ListView listView = (ListView) inflater.inflate(R.layout.my_top_layout, container, false);
View header = inflater.inflate(R.layout.header_layout, null);
// Initialize your header here.
listView.addHeaderView(header, null, false);
BaseAdapter adapter = // ... Initialize your adapter.
listView.setAdapter(adapter);
// Just as a bonus - if you want to do something with your list items:
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// You can just use listView instead of parent casted to ListView.
if (position >= ((ListView) parent).getHeaderViewsCount()) {
// Note the usage of getItemAtPosition() instead of adapter's getItem() because
// the latter does not take into account the header (which has position 0).
Object obj = parent.getItemAtPosition(position);
// Do something with your object.
}
}
});