在ScrollView中使用ListView可以通过以下步骤实现:
以下是一个示例代码:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
public class CustomAdapter extends BaseAdapter {
private List<String> dataList;
private Context context;
public CustomAdapter(List<String> dataList, Context context) {
this.dataList = dataList;
this.context = context;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(dataList.get(position));
return convertView;
}
}
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
List<String> dataList = new ArrayList<>();
// 添加数据项
dataList.add("Item 1");
dataList.add("Item 2");
dataList.add("Item 3");
// ...
CustomAdapter adapter = new CustomAdapter(dataList, this);
listView.setAdapter(adapter);
// 设置ListView的高度为自适应内容高度
setListViewHeightBasedOnChildren(listView);
}
private void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
这样,你就可以在ScrollView中使用ListView了。ListView会根据数据项的数量自动滚动,并且可以在其中显示大量的列表项。
领取专属 10元无门槛券
手把手带您无忧上云