向LinearLayout添加两个ListView仅首个显示,求问题原因
Hey there! Let's break down why only one of your ListViews is showing up in the LinearLayout, and how to fix it.
核心原因
The main issue here is the LayoutParams you're using for both ListViews. You've set:
ConstraintLayout.LayoutParams newParams = new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT);
First off, using ConstraintLayout.LayoutParams for views inside a LinearLayout is incorrect—you should use LinearLayout.LayoutParams instead, since the parent layout dictates the valid layout rules.
But the bigger problem is the MATCH_PARENT height. By default, LinearLayout uses a vertical orientation. When you add a view with MATCH_PARENT height to it, that view will take up the entire available height of the LinearLayout. The second ListView gets pushed completely out of the visible area because there's no space left.
Fixes to Try
1. Use WRAP_CONTENT for ListView Height (Quick Fix)
Change the height parameter in your LayoutParams to WRAP_CONTENT—this makes each ListView only take as much space as it needs to display its content:
// Update the LayoutParams to use WRAP_CONTENT for height LinearLayout.LayoutParams newParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Apply to both ListViews listView.setLayoutParams(newParams); listView2.setLayoutParams(newParams);
⚠️ Note: Using WRAP_CONTENT with ListView can cause performance issues for large datasets, since it has to measure all items upfront. This works best for small lists.
2. Use Layout Weight to Split Space (Better for Equal Height)
If you want both ListViews to share the available space equally, use LinearLayout.LayoutParams with a weight value. Set the height to 0dp (so weight takes over) and assign a weight of 1 to each:
// Create LinearLayout-specific params with weight LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0, 1.0f); // Apply to both ListViews listView.setLayoutParams(listParams); listView2.setLayoutParams(listParams);
Make sure your LinearLayout in XML has android:orientation="vertical" set—this tells the layout to distribute the weight along the vertical axis.
3. Switch to RecyclerView (Recommended Long-Term)
ListView is an older widget and has limitations with flexible layouts like this. RecyclerView is designed to handle these scenarios better, with more flexibility in item layout and better performance. It's the modern replacement for ListView, so it's worth migrating to if you're working on a newer project.
内容的提问来源于stack exchange,提问作者cppsvx

